The JavaScript Diaries: Part 15
By Lee Underwood
May 14, 2007
One of the things that we can do with JavaScript is display and manipulate the date and time. This can be useful in many ways, such as calculating the days between dates, showing new items on your Web site and calculating shipping dates. In this installment we'll take a look at the JavaScript Date() object and learn how to utilize it in our scripts.
Living on JavaScript Time
JavaScript uses the date of midnight, January 1, 1970 UTC as a starting point for all of its calculations (also the same date used by Unix and Java). Since it's the starting date from which Unix time is measured, it's known as the Unix epoch, epoch time, or just the epoch. Anything prior to that date is declared as a negative value. While we might calculate the days between two calendar dates, the numbers used in the calculations are determined by the number of milliseconds that have passed since the epoch time (not counting leap seconds).
All epoch time is measured in units of milliseconds. To ensure accuracy, all calculations should be performed on that basis. These calculations are done using the getTime() method. For instance, using a specific time — Friday, September 22, 2006, 3:57:12 PM, we can calculate the time as 1,158,955,032,531 milliseconds from January 1, 1970. (Boy, time sure flies!) In order to determine how many years it's been since the epoch, we could use the following calculation:
That will return a value of 36.75023885004439 (using our date above). That would be 36 years, 8 months, and 21 days. (I used another script to get the exact amount of time.) Here's how it works (this is a rough calculation and doesn't account for leap years):
First, we created a new instance of the Date() object and gave that value to the newly created variable d
Next, we used the getTime() method of the Date() object to obtain the time from the variable d.
Then, we created a variable named days and gave it the value of the calculation that follows it.
First, we took the variable e and divided it by 1000 — because the time is in milliseconds, which gives us the number of seconds.
Then we divided that number by 60 — the number of seconds in a minute.
Next we divided that number by 60 — the number of minutes in an hour.
Then we divided that number by 24 — the number of hours in a day.
And then we divided that number by 365 — the number of days in a year.
Chance are you're pretty confused by now so let me try to make it simpler (with some help from Danny Goodman). The following calculations (presented as variables) should make it easier for you to see the relationship.
That should be easier to understand. You can also use that for your own calculations.
The Date Object
JavaScript uses the Date() constructor to obtain and manipulate the day and time in a script. The information is taken from the user's computer and is only as accurate as the user's system. It's important to remember that as it will determine the outcome of your scripts.
It's possible to manipulate the date using Coordinated Universal Time (UTC), which is basically the same as Greenwich Mean Time (GMT). (Actually, GMT is measured from noon whereas UTC is measured from midnight. However, few use the noon measurement and refer to GMT as if it were actually UTC.)1 That's a bit beyond our basic tutorial so we won't worry too much about that now. We'll look at that later, in a more advanced tutorial.
Note also that the Date() object is case sensitive. Failure to observe that little fact will result in many headaches.
Creating Dates
To use the Date() we need to use the new keyword. If you remember our discussion in Part 11, the new keyword creates a new instance of the object. In this case it means that we take the Date() object, make a copy of it and give that copy a name. It's a new "instance" or "occurrence" of the Date() object. That would be done like this:
As I said, this creates a new instance of the Date() object. It's important to remember that it contains the value of the user's system date at the time of execution. The date/time is not updated unless manipulated by the script. For instance, if I issued the above statement right now, it might contain the date/time data as listed below:
Fri Sep 22 2006 14:29:28 GMT-0400 (Eastern Standard Time)
While this will be fine in many situations, it's important to remember that, without manipulation, the data is not constantly being updated as the script is running. If we wanted to display the data as is, we could write the following:
which would print as follows:
The date is Friday, September 22, 2006
and the time is 2:29:28 PM
Let's take a look at what we did here.
First, we declared a new instance of the Date() object (using the new keyword) and gave its value to a newly created variable named d.
Next, we created two document.write statements.
The first one uses the toLocaleDateString() method. (We'll look at the Date() object's methods in a moment.) This tells the script to display the date portion of the variable using the format of the user's computer system.
The second one, toLocaleTimeString(), tells the script to display the time portion of the variable using the format of the user's computer system.
Let's take a look at the methods available when using the Date() object. From there we will look at how to apply them.
The Date() object utilizes several methods, which are detailed below. Note that the time is given either according to local time (the time as stated on the visitor's computer) or according to universal time. A few of the methods have been deprecated, and have been marked as such. They are shown here so you will know them if you run into an older script or tutorial.
[ Taken from Core JavaScript Reference 1.5 ]
Name
Description
getMilliseconds()
Returns the milliseconds in the specified date according to local time. [ 0 - 999 ]
getSeconds()
Returns the seconds in the specified date according to local time. [ 0 - 59 ]
getMinutes()
Returns the minutes in the specified date according to local time. [ 0 - 59 ]
getHours()
Returns the hour in the specified date according to local time. [ 0 - 23 ]
getDay()
Returns the day of the week for the specified date according to local time. [ 0 (Sunday) to 6 (Saturday) ]
getDate()
Returns the day of the month for the specified date according to local time. [ 1 - 31 ]
getMonth()
Returns the month in the specified date according to local time. [ 0 (January) to 11 (December) ]
getYear() deprecated
Returns the year in the specified date according to local time. (Use getFullYear instead.)
getFullYear()
Returns the year of the specified date according to local time.
getTime()
Returns the numeric value corresponding to the time for the specified date according to local time.
getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.
getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal time. [ 0 - 999 ]
getUTCSeconds()
Returns the seconds in the specified date according to universal time. [ 0 - 59 ]
getUTCMinutes()
Returns the minutes in the specified date according to universal time. [ 0 - 59 ]
getUTCHours()
Returns the hours in the specified date according to universal time. [ 0 - 23 ]
getUTCDay()
Returns the day of the week in the specified date according to universal time. [ 0 (Sunday) to 6 (Saturday) ]
getUTCDate()
Returns the day of the month in the specified date according to universal time. [ 1 - 31 ]
getUTCMonth()
Returns the month according in the specified date according to universal time. [ 0 (January) to 11 (December) ]
getUTCFullYear()
Returns the year in the specified date according to universal time.
setMilliseconds()
Sets the milliseconds for a specified date according to local time. [ 0 - 999 ]
setSeconds()
Sets the seconds for a specified date according to local time. [ 0 - 59 ]
setMinutes()
Sets the minutes for a specified date according to local time. [ 0 - 59 ]
setHours()
Sets the hours for a specified date according to local time. [ 0 - 23 ]
setDate()
Sets the day of the month for a specified date according to local time. [ 1 - 31 ]
setMonth()
Sets the month for a specified date according to local time. [ 0 (January) to 11 (December) ]
setYear() deprecated
Sets the year for a specified date according to local time. (Use setFullYear instead.)
setFullYear()
Sets the full year for a specified date according to local time.
setTime()
Sets the value of a Date object according to local time.
setUTCMilliseconds()
Sets the milliseconds for a specified date according to universal time. [ 0 - 999 ]
setUTCSeconds()
Sets the seconds for a specified date according to universal time. [ 0 - 59 ]
setUTCMinutes()
Sets the minutes for a specified date according to universal time. [ 0 - 59 ]
setUTCHours()
Sets the hour for a specified date according to universal time. [ 0 - 23 ]
setUTCDate()
Sets the day of the month for a specified date according to universal time. [ 1 - 31 ]
setUTCMonth()
Sets the month for a specified date according to universal time. [ 0 (January) to 11 (December) ]
setYear()
Sets the year for a specified date according to local time.
setUTCFullYear()
Sets the full year for a specified date according to universal time.
toGMTString() deprecated
Converts a date to a string, using the Internet GMT conventions. (Use toUTCString instead.)
toLocaleString()
Converts a date to a string, using the current locale's conventions.
toLocaleDateString()
Returns the "date" portion of the Date as a string, using the current locale's conventions.
toLocaleTimeString()
Returns the "time" portion of the Date as a string, using the current locale's conventions.
toString()
Returns a string representing the specified Date object. Overrides the Object.toString method.
toUTCString()
Converts a date to a string, using the universal time convention.
parse()
Returns the number of milliseconds in a date string since January 1, 1970, 00:00:00, local time.
UTC()
Returns the number of milliseconds in a Date object since January 1, 1970, 00:00:00, universal time.
toSource()
Returns an object literal representing the specified Date object; you can use this value to create a new object. Overrides the Object.toSource method.
valueOf()
Returns the primitive value of a Date object. Overrides the Object.valueOf method.
Each of the methods listed is self-explanatory. Let's look now at how to use some of them.
To display the date, you could use the following function:
It would display as: (Remember, the date is only as accurate as the settings in your user's computer system.)
Let's take a look at what we did:
First, we created a function named displayDate()
Then, we declared the variable thisDate. We created a new instance of the Date() object and assigned it to the thisDate variable.
Next, we declared the variable curDay and gave it the value of the current day of the month, which is derived from the value of the variable thisDate, using the dot operator in conjunction with the getDate() method.
We then declared the variable curMonth and gave it the value of the current month, which is derived from the value of the variable thisDate, using the dot operator in conjunction with the getMonth() method..
Note that we added "1" to the value of the method before assigning it to the month variable. This is because months are counted, starting with "0", i.e. January = "0", December ="11". By adding the "1", it now becomes the current month. (We would need to do it with the day of the week also, if we were using it.)
Then, we declared the variable curYear and gave it the value of the current year, which is derived from the value of the variable thisDate, using the dot operator in conjunction with the getFullYear method.
Finally, we created a string to print out the current date, using a document.write statement.
In order to display the date on the page, we placed a call to the function in the place we wanted to display the date.
Sounds a bit complicated but it's not. Once you get the hang of it, it's quite simple. Let's apply our knowledge of arrays and see how to spice it up:
It would display as:
See? It's actually quite simple. First we created a set of parallel arrays, one for the month and one for the day of the week. Since the array indexes are already assigned to the given months and days, we don't need to add "1" to the number. Next, we declared the variables and assigned values to them. Finally, we used a document.write to format and display the date.
Let's look at some other ways to use the Date() object methods.
Let's take a script borrowed from Doc JavaScript and adapt it a bit for our purposes. We're going to write a script which will tell you what day of the week you were born.
Most of this should look pretty familiar. You've got your basic array, conditional statements, prompt and alert boxes. Now let's break it down and see what we did.
First, we created a function named findDay(). This makes it easier for us to access the script.
Next, we declared a variable named ar and gave it the value of an array.
We then populated the array with seven elements, representing the seven days of the week.
Then, we declared a variable named yourDay. For it's value, we gave it a prompt statement.
The first line checks to see if the user has entered any data. If the box is blank or still contains the default message ("Enter Date"), then an alert box will display the message, "You didn't enter anything."
If the user did enter data, then the next statement is executed, which will tell the user what day of the week he/she was born on.
Finally, we added a button on the page to execute the script.
With a bit of forethought, you should be able to handle most of these scripts. If it gets a bit out of hand, we have forums where you can ask for help.
Now, let's find out how many days are left in the current month. A variation of this script might come in handy when prorating rental fees or calculating the number of days left in a sale. Here's the script (adapted from JavaScript Source).
And this is what it looks like:
This one should be pretty easy to understand. The first four variables are like the previous examples. The next one, monarr, is given the value of an array whose elements are the length of each month, from January to December. There's also a formula for determining a leap year. You might want to add this to your collection of snippets. (You do have a collection of snippets, don't you?)
In the script above, if the year is a leap year, then the second element in the array of the variable monarr is equal to 29. If you think about it, the array represents the number of days in the months, beginning with January, which has an index number of "0". That means that the second element in the array (monarr[1]) is February, with an index number of "1." The leap year calculation then changes its array element to "29" for this calculation.
The "Y2K" Problem
You will find many scripts have what is called the "Y2K fix." That means they will have something like the following code:
This was created in order to allow scripts to deal with years beyond 1999. However, with the introduction of the Standard ECMA-262 ECMAScript Language Specification this problem was eliminated with the use of the getFullYear method.
(This is why the getYear method is deprecated. This also applies to the setYear method, which was deprecated in favor of the setFullYear method.)
If you come across a script like the one above, just change the getYear method to the getFullYear method and remove the following line:
Going Further
That wraps up this section on the Date() object. As you can see it has many different applications. I didn't go into too much depth as I wanted you to be able to digest this in small bits. (Perhaps I'll do an advanced tutorial at a later date, as I mentioned earlier.) Don't be afraid to get involved in calculations using this object. Just take your time. Also, be sure to dissect other scripts to see how they work. Once you break them down, it's not too difficult to see what makes them tick. You can find a large number of them over at JavaScript Source and JavaScripts.com.