Suite101

Using the JavaScript Date Object

How-To Java Script Tutorial Article for Processing Dates and Offsets

© Guy Lecky-Thompson

This JavaScript tutorial article lesson is an introduction to the JavaScript Date Object, and how to use it to calculate dates, date offsets, and format date strings.

The JavaScript Date Object is very useful in manipulating date values, and then retrieving them in a variety of formats.

This article describes how to:

  • Instantiate a date object;
  • Retrieve the current date;
  • Format a date string;
  • Calculate a new date.

The internal format of the date is the same as in C and C++, in other words, a long integer containing the offset from a specific moment in time, in milliseconds. Luckily, the date object in JavaScript provides an easy way to manipulate this value, and retrieve the various components.

Instantiating the JavaScript Date Object

To instantiate a date object to the current date and time, the following code is all that is required:

var myDate = new Date();

Until the Date() object value is assigned to the variable, the variable does not contain a valid date. Indeed, due to the typing of the JavaScript language, the type of the myDate variable is not even known until an assignment is made.

Once the date object is instantiated, there are several functions that can be used to set the individual components of the object. The most common are:

  • setDate ( <day of month between 1 and 31> )
  • setMonth ( <month of year between 0 and 11> )
  • setFullYear ( <four digit year> )
  • setHours ( <hour of day between 0 and 23> )
  • setMinutes ( <minutes of hour between 0 and 59> )
  • setSeconds ( <seconds of minute between 0 and 59> )

In addition, there are some functions for setting a time offset, which this article covers in the Calculating New Dates section, below.

Retrieving the Current Date and Time

For each of the set<component> functions in the above list, there is a corresponding get<component> that returns the appropriate numerical value. Therefore, the following code will retrieve the current month of the year, and use it to display the month name.

var monthNames
= new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var myDate = new Date();
document.write ( monthNames[myDate.getMonth] );

The same trick can be pulled to retrieve the day of the week, and convert it to a day name. This uses the function getDay, which returns a number between 0 and 6. The value 0 is assigned to Sunday. As long as this is respected, the code follows the same general layout as above.

Formatting JavaScript Date Strings

Using the above code to get numbers and convert them to names is tedious. If a string is needed, containing the current date and time, then the JavaScript Date object overrides the default toString method to produce a date that is somewhat more readable:

document.write ( myDate.toString() );

The above statement will output a string similar to:

Wed Jun 18 11:00:00 (Central European Time)

The return value can also be assigned to a string object, and the split() function used to break it down into individual components.

Calculating New Dates

When using the Date object to calculate new dates, the two most important functions are:

  • setTime ( <time offset to add> )
  • parse()

The first of these will modify the date object such that it contains the correct date with respect to the number of milliseconds since 1 January 1970, provided as a parameter. The second function will take a string representation (such as that returned by the .toString method) and return the appropriate number of milliseconds.

So, to create a date object that is set to a time 7 days from the time at which it was created, the following code is used:

var dateOffset = (24*60*60*1000) * 7;
var myDate = new Date();
myDate.setTime(myDate.getTime() + dateOffset);

In the above fragment, the companion to .setTime, .getTime is used to retrieve the correct number of milliseconds.

Two dates can not be added together in any other way, so unlike other languages, it is not possible to create a date object populated with an offset, and then add it to another native date object.


The copyright of the article Using the JavaScript Date Object in Javascript/Java Programming is owned by Guy Lecky-Thompson. Permission to republish Using the JavaScript Date Object in print or online must be granted by the author in writing.



Post Your Comment
2500 characters left
NOTE: Because you are not a Suite101 member, your comment will be moderated before it is viewable.
What is 6+1? Incorrect, please resolve x + y!


Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo