1.19 Skill builder: Telling Time

Finding the time and date

You can use Javascript to read and set dates. These dates are based on the clock of the user's computer, which can be inaccurate. But it is good enough for many purposes.

Getting the time

To read the time, you have to create a new Date() object:

If you use .innerHTML to print out dateObject, you will see it displayed in a form that is half-human, half computer readable:

Date() functions

This will do just fine for many cases, such as creating computer log entries. But say that you want to display the time in different languages, or even in more humanly-readable English. Then you have to use Date() functions on your dateObject:

Always start off by assigning a Date() object to a variable:

Then you can use any of the following functions (and more):

functions for Date() objects
function description range button example
dateObject.getHours() gets the hour of the day 0 → 23 (24 hour clock)
dateObject.getMinutes() gets the number of minutes 0 → 59
dateObject.getSeconds() gets the number of seconds 0 → 59
no function in Javascript am or pm build your own code
dateObject.getDay() gets the day of the week 0 → 6
dateObject.getMonth() gets the month of the year 0 → 11
dateObject.getDate() gets the day of the month 1 → 31
dateObject.getFullYear() gets the current year four digit year

Translating into human language

Note that you are only given numbers instead of words for each function. This is intentional so that programmers can write code for different languages and other purposes.

Also note that days of the week and months of the year return the actual number - 1. This is very handy if we want to display the month or weekday information using an array. For example, say we have an array set up:

Now we can get a human-readable weekday value with the following expression:

You can do this with the months, converting days of the month to "1st", "2nd", "3rd",... and to quickly display whether something is am or pm.

Saving your work

Download the template and rename it to your last name, such as "1.19S-TellingTime-LastName.html".

The assignment

In this assignment you will add code to the template to create a program that displays the time in the following form:



Please keep in mind the following:

  1. Start by initializing the arrays. I have provided some information for you to help. How will will you convert this into arrays?
  2. Remember to use intelligent variable names, such as: dayOfTheWeek.
  3. Remember to split your functions into separate parts: INIT, INPUT, PROCESS, and OUTPUT.
  4. In your descriptive comments for each function, indicate whether the function is for INIT, INPUT, PROCESS, or OUTPUT.
  5. Use onload="mainProcedure();" to start the process rolling, not a button.
  6. Use arrays to convert the information from the Date() functions into human-readable text
  7. Is there another way to deal with am/pm?