Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

4.4. The Date Object

In JavaScript, you use the Date object to create instances of dates. Once you have a date object instance, you can use several methods to access or modify the date (or components of the date) such as the year, day, and month.

Creating a date without passing in any parameters produces a date based on the client machine’s date and time:

var dtNow = new Date();

Or, you can pass in optional parameters to the Date constructor to create a specific date. One option is to pass in the number of milliseconds since January 1, 1970 at 12:00:00:

var dtMilliseconds = new Date(5999000920);

The preceding code snippet results in the following date:

Wed, 11 Mar 1970 10:23:20 GMT

You can also use a string to create a date as long as you use the proper date format:

var newDate = new Date("March 12, 1980 12:20:25");

You can forgo the time in the string and just get a date with times set to zeros:

var newDate = new Date('March 12, 2008');

You can also pass in each value of the date as integers, in order of year, month (as 0 to 11), day, hour, minutes, seconds, and milliseconds:

var newDt = new Date(1977,11,23);
var newDt = new Date(1977,11,24,19,30,30,30);

The Date object instance methods feature several get and set methods for retrieving or setting specific components of the date. Each of the following gets specific values from the date according to local times:


getFullYear

The four-digit year


getHours

The hours component of the date/time


getMilliseconds

The milliseconds component of the date/time


getMinutes

The minutes component of the date/time


getMonth

The month, as a number between 0 and 11 inclusive


getSeconds

The seconds component of the date/time


getDay

Returns the number representing the day of the week, starting with 0 for Sunday and ending with 6 for Saturday


getDate

Returns the day of the month

Here are the Coordinated Universal Time (UTC) equivalents:

  • getUTCFullYear

  • getUTCHours

  • getUTCMilliseconds

  • getUTCMinutes

  • getUTCMonth

  • getUTCSeconds

  • getUTCDay

  • getUTCDate

Most of the get methods have equivalent set methods that set a component’s value within a Date. An example would be setYear to set the year, setSeconds to set the seconds, or setUTCMonth to set a UTC month. The only method that doesn’t have an equivalent set method is getDay. Also, two methods are deprecated, meaning they won’t be available in the future. These are getYear and setYear.

Another method, getTimezoneOffset, returns the number of minutes (+ or –) of the offset of the local computer from UTC. Because I’m writing this in St. Louis, which is in UTC-5, I would get a value of 300 when calling this method against a local time date.

Six methods convert the date to a formatted string:


toString

Outputs the string in local time


toGMTString

Formats the string using GMT standards


toLocaleDateString and toLocaleTimeString

Output the date and the time, respectively, using the locale


toLocaleString

Converts the string using the current locale


toUTCString

Formats the string using UTC standards

Also, three static methods are available directly on the Date object. Date.now returns the current date and time; Date.parse returns the number of milliseconds since January 1, 1970; and Date.UTC returns the number of milliseconds given the longest form of the constructor, described earlier:

var numMs = Date.UTC(1977,11,24,30,30,30);

NOTE

Date.now is not standard. Creating a date primitive without using the new constructor also returns the current time:

var rightNow = Date();

Example 4-10 demonstrates several of the Date methods, including those that set date components, and methods to display the derived date.

Example 4-10. Several string setting and formatting Date methods

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Date</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
//<![CDATA[

function testingDate() {

   // new date
   var dtNow = new Date();

   // set day, month, year
   dtNow.setDate(18);
   dtNow.setMonth(10);
   dtNow.setYear(1954);
   dtNow.setHours(7);
   dtNow.setMinutes(2);

   // output formatted
   document.writeln(dtNow.toString() + "<br />");
   document.writeln(dtNow.toLocaleString() + "<br />");
   document.writeln(dtNow.toLocaleDateString() + "<br />");
   document.writeln(dtNow.toLocaleTimeString() + "<br />");
   document.writeln(dtNow.toGMTString() + "<br />");
   document.writeln(dtNow.toUTCString());
}                                               
//]]>                                           
</script>                                
</head>                                  
<body onload="testingDate()">
<p>Some page content</p>
</body>
</html>

					  

The result of running Example 4-10 in Firefox 3.1 is:

Thu Nov 18 1954 07:02:19 GMT-0600 (CST)
Thu Nov 18 07:02:19 1954
11/18/1954
07:02:19
Thu, 18 Nov 1954 13:02:19 GMT
Thu, 18 Nov 1954 13:02:19 GMT

Given so many date options, it might be puzzling to figure out which specific locale to use in an application. I’ve found that a good rule of thumb is to reference everything in the web page reader’s local time if her actions are isolated—such as when placing an order at an online store. However, if the person’s actions are in relation to the actions of others, especially within an international audience (such as a weblog for comments), I recommend setting times to UTC to maintain a consistent framework for all of your readers.