JavaScript Date Object

From Techotopia
Revision as of 13:51, 20 June 2007 by Neil (Talk | contribs)

Jump to: navigation, search
PreviousTable of ContentsNext
JavaScript String ObjectJavaScript Math Object


The JavaScript Date object enables you to work with, and manipluate time (and no, it doesn't enable you to travel back through time to buy a lottery ticket with this week's winning numbers - if it did that I would have already done it, and would be sitting on beach somewhere instead of writing this book).

The Date object enables the JavaScript developer to create a Date object initialized to a specific time and date, or to create a date object that reflects the current system time on the computer on which the browser is running. There are two important things to note when working with the JavaScript Date object. Firstly, when reading the date and time of the user's computer you are completely at the mercy of the user's ability to set and maintain the correct day and time on their computer. Secondly, whilst you can read the system date and time set on the user's computer, and change those settings within your Date object instance, you cannot change the computer's system date and time. No matter what methods you call or properties you change on your Date object, the user's system date and time remain unaltered.



Contents


Understanding System Time

Rather than understanding the concepts of dates and times, computers essentially record the passage of time since a particular baseline date and time (often referred to as the epoch). The epoch date, and unit of measurement for elapsed time depends on the system being used. A Windows system, for example, counts the number of 100-nanoseconds since January 1, 1601 00:00:00. A UNIX or LINUX based system, on the other hand, counts the number of seconds that have elapsed since January 1, 1970 00:00:00.

When working with JavaScript it is useful to know that when the current date is requested it is returned as the number of milliseconds that have elapsed since January 1, 1970, 00:00:00. As you will see later in this chapter, the JavaScript Date object contains plenty of methods that make it easy for developers to set and read the time using human readable date formats.

Creating a JavaScript Date Object

A javaScript Date Object is created much like any other object in JavaScript, using the new keyword and some optional arguments (for an overview of Objects in JavaScript see JavaScript Object Basics). The syntax for creating an instance of a Date object is as follows:

var myDate = new Date(Optional Parameters);

The following table shows the different parameter options that are accpted by the Date object at Create time:

ParametersDescriptionExample
NoneCreates a date object set to the users current system timevar currentDate = new Date()
month dd, yyyy hh:mm:ss'Sets Date object to specified month, day and time. Omitted values are set to zero var myDate = new Date("December 1, 2009, 12:01:00")
mm, dd, yyyyInitializes date object to the specified month, day and year.var myDate = new Date(07, 24, 2008)
yyyy, mm, ddInitializes the date object to the specified month, day and yearvar myDate = new Date (10, 27, 2007, 10, 20)

Setting the Time and Date of the JavaScript Date Object

Once an instance of a date object has been created it is often necessary to change specific properties (such as the time or the year) of that object. As one might expect, JavaScript includes a number of methods in the Date object to facilitate this:

MethodDescriptionExample
setDate()Sets the day of the monthmyDate.setDate(20)
setMonth()Sets the month of the year. Note that that this is a zero based value (i.e 0 = January)myDate.setMonth(10)
setFullYear()Sets the year using full 4 digits (i.e 2008).myDate.setMonth(2010)
setTime()Sets the time by specifying the number of milliseconds since 00:00:00 on January 1, 1970myDate.setTime(10000)
setHours()Sets the hours property of the Date objectmyDate.setHours(20)
setMinutes()Sets the minutes property of the Date objectmyDate.setMinutes(42)
setSeconds()Sets the seconds property of the Date objectmyDate.setSeconds(59)

As discussed previously, it is important to keep in mind that you are only setting the time and date properties inside the instance of the Date object with these methods. There is no way for a JavaScript script to change the system date and time of the computer on which the browser is running.

Reading the Date and Time from a JavaScript Date Object

Just as with setting the properties of a JavaScript Date Object, there are a number of ways to read the date and time properties of the Date. One, less useful, way is to use the getTime() method of the Date object. The getTime() object returns the date and time of the user's system represented by the number of milliseconds since 00:00:00 on January 1, 1970. For example:

var today = myDate.getTime()

would return a value similar to 1182356520000 which doesn't mean an awful lot to a human being. Another methods is to read each of the individual Date properties using the getDate(), getMonth(), getFullYear(), getHours(), getMinutes(), getSeconds() methods:


var myDate = new Date ("June 20, 2007 12:00:00");

document.write (myDate.getDate() + " " + myDate.getMonth() + " " + myDate.getFullYear() + " " + myDate.getHours() 
+ " " + myDate.getMinutes() + " " + myDate.getSeconds());

// Outputs 20 5 2007 12 0 0

It is also possible to obtain the time in human readable form relative to a number of different time zones.

UTC Time

Coordinated Universal Time (UTC) is the equavalent to Greenwich Mean Time (GMT). Using the toUTCString() method of the JavaScript Date Object will return to you the current UTC date and time. Supposing the visitor to your web page is in the United States in Eastern Standard Time (EST) and the local time is 12:00pm and the script on your web page performs the following:


var myDate = new Date (); // Get the date of the user's system

document.write ("Current (UTC) Time is " + myDate.toUTCString());

you should expect to see the following text appear because 12:00 EST is really 16:00 UTC.

Current (UTC) Time is Wed, 20 Jun 2007 16:00:00 GMT

Finding the Time Zone Offset and Getting Local Time

It is often useful to be able to find out the time zone offset (meaning the number of hours ahead or behind UTC) of a web site visitor. JavaScript provides the getTimezoneOffset() method which, as the name suggests, returns the number of minutes difference between the client (i.e where the browser is being run) and UTC:


var myDate = new Date (); // Get the date of the user's system

document.write ("Hours Offset from UTC is " + myDate.getTimezoneOffset());

If the visitor to your web site used Eastern Standard Time then the above would report the time offset as 240 minutes. You can, ofcourse, convert this to hours simply by dividing by 60. The following displays the time offiset as 4 hours:


var myDate = new Date (); // Get the date of the user's system

document.write ("Hours Offset from UTC is " + myDate.getTimezoneOffset()/60 );

The local time of the system on which the browser is running can be obtained using the toLocaleString() method of the JavaScript Date Object. This method returns a string correct for the lcoal time zone. Assuming, once again, a visitor located on the East coast of the United States and the following the following script fragment:


var myDate = new Date (); // Get the date of the user's system

document.write ("Local Time is " + myDate.getLocaleTime());

you should expect to receive output as follows:

Wed 20 Jun 2007 12:00:00 PM EDT



PreviousTable of ContentsNext
JavaScript String ObjectJavaScript Math Object