Javascript Dates-The Complete Reference

Filed: Mon, Apr 23 2007 under Programming|| Tags: reference date javascript julian countdown

Of all the core Javascript objects, I find Dates to be the most fascinating. Once you learn a few small tricks everything about Javascript Dates just seem to fall into place and you find that there's really nothing at all that you can't do with them, quickly, and easily.

This reference will cover the Javascript Date Object, how it stores Dates, how you can manipulate them, create calendars, countdown timers, prototype them to add your own functionality, as well as provide a complete method reference.

Julian Dates

Julian Dates are a method of referencing time and dates based on how much time has passed since an arbitrary number in the past. For instance, days have presently passed this year. If we know that January 1 begins on a , then we know that day 2 represents a in January. If we know there are 31 days in January then we know that day 32 represents the first of February and we can figure out that February 1st fell on a .

Javascript (and most languages) handle dates exactly as described above, only in much grander fashion. The epoch or starting point of Javascript's date system isn't January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it doesn't count just days! No Javascript counts the number of milliseconds that have passed since January 1, 1970 and presently that number is .

Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers indicate dates after 1970 and negative numbers indicate dates prior to 1970. For instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript counts in milliseconds and there are 1000 milliseconds in a single second so -1000 represents 1 second.

By a great coincidence Unix also uses January 1, 1970 as it's epoch date which means a timestamp in Javascript will match a timestamp on your server as long as you take some care with the timezones!

It will be quite a while before humanity has to worry about running out of dates! Javascript can readily handle around 285,616 years on either side of the 1970 epoch.

Creating A New Date (Parsed)

To create a new Date all you have to do is to ask for one!

var myFirstDate = new Date();

This will create a new date object and since we did not specify a specific date or time, the date will be equal to the instant it was created.

The Javascript Date Object has a very powerful date parser. While there are several ways to create and set Dates. The one you're most likely to use is simply to specify the date itself, as a string, when creating a new date.

var myDate = new Date('January 16, 1988');

Since we didn't specify a time the Date which is created will be for midnight in the browser's timezone on January 16, 1988.

var myDate = new Date('January 16, 1988 2:54:16 pm');

Here we specify a specific time (note that there's a space between the time and pm). Since we didn't specify a timezone the browser will use the user's timezone. We could also have used millitary time (14:54:16).

Here we'll actually specify a time zone GMT in this case and below we'll print it out.

var myDate = new Date('January 16, 1988 2:54:16 pm GMT');

Unless you actually live in the Greenwich Mean Timezone, the date requested and the date printed are unlikely to match. The created date is actually 2:54:16 in the GMT timezone, however when we printed the date out, since we didn't specify anything special, the date was printed in the Browser's time zone so the browser did a little conversion for us to ensure the time we printed was the ACTUAL time relative to the browser.

That's a little confusing so let's try for something different. Every New Years Eve, the city of New York holds a big celebration and the ball is dropped at precisely midnight in the eastern timezone. So lets create a date for that event.

var myDate = new Date('January 1, 2000 EST');

Since we didn't specify a time, Javascript will assume midnight for us, we did specify a time zone so the actual time will be midnight in the eastern time zone.

Now when we print the date out we'll get that little timezone conversion and you can see what time the ball will be dropping in your timezone! (of course people in the eastern timezone will see the correct time).


Creating A New Date (arguments)

You can also create a new date by passing the date values as arugments to the Date object. The arguments are Year, Month, Date and optionally hours, minutes, seconds, and milliseconds. The first argument, year, is special. If it's a string the Date object will try to parse it (see previous section), if it's a long integer it will try to use it as a julian number. If there are more than one argument it will build the date from your supplied arguments.

var d1 = new Date('January 1, 1970'); // Date as a parse
var d2 = new Date(0);                 // Date as a julian number
var d3 = new Date(1970, 0, 1);        // Date as arguments

Notice we use zero as the month when creating d3, that's because Javascript months go from 0 to 11 where January is zero. This is a pretty big gotcha if you're not careful!

The argument list is as follows…

dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);

Working With Julian Day Numbers

Working with Julian Dates requires division and modulus. Division will discard the portion of the date you no longer need and modulus (which is the remainder of division) will return the portion of the date you are looking for.

Most people don't need milliseconds when doing date calculation, so we just divide the Julian Date Number by 1,000. So if we have a Julian Day Number of 1,177,303,066,354 then dividing this by 1,000 will give us a day number of 1,177,303,066 -- a number which no longer holds information about the milliseconds in the date.

To get the number of seconds this represents, we take the modulus of 60 because there are 60 seconds in a minute.

var dayNumber = 1177303066;
var seconds = dayNumber % 60;  // seconds=46

Now that we have the number of seconds we discard the seconds from the Julian date by dividing it by 60.

var dayNumber = 1177303066;
var seconds = dayNumber % 60;  // seconds=46
dayNumber = dayNumber/60;      // dayNumber = 19,621,717

So now our day number has been stripped of milliseconds and seconds. We can find out how many minutes the number represents by taking the modulus of 60 since there are 60 minutes in an hour.

var dayNumber = 1177303066;
var seconds = dayNumber % 60;  // seconds=46
dayNumber = dayNumber/60;      // dayNumber = 19,621,717
var minutes = dayNumber % 60;  // minutes=37  

And we can discard the minutes from the original number by dividing it by 60. What remains are hours and days. We can get the hours by taking the modulus of 24 since there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours, leaving only the number of days.

var dayNumber = 1177303066;
var seconds = dayNumber % 60;  // seconds=46
dayNumber = dayNumber/60;      // dayNumber = 19,621,717
var minutes = dayNumber % 60;  // minutes=37
dayNumber = dayNumber/60;      // dayNumber = 327,028
var hours = dayNumber % 24;    // hours = 4
dayNumber = dayNumber/24       // dayNumber = 13,626

Or 13,624 days between January 1, 1970 and

Countdown Timers In Javascript

In the previous section we broke a day number out into its component milliseconds, seconds, minutes, hours, and days. The number we used was the number of milliseconds that had elapsed since January 1, 1970. But we could just as easily have used another date. Lets take the difference between now and the end of the year.

var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;

This code creates two julian dates, now and newYear. By subtracting now from newYear we get an integer which represents the difference between the two dates, specifically:

We can use division and modulus to extract the time from this number just like we did in the previous section only now we're computing the difference between now and the new year instead of a date and January 1, 1970.

This article is generating now and newYear in real-time so the values below are the actual values until the new year!

var now = new Date();
var newYear = new Date('January 1, '+(now.getFullYear()+1));
var diff=newYear-now;
var milliseconds=Math.floor(diff % 1000);   
    diff=diff/1000;            
var seconds=Math.floor(diff % 60);
    diff=diff/60;
var minutes=Math.floor(diff % 60);
    diff=diff/60;
var hours=Math.floor(diff % 24);
    diff=diff/24;
var days=Math.floor(diff);

This gives us a value of

Making a Timer

In the example above now is equal to the instant it is created while newYear is a constant value, always equal to January 1 of next year. So it's actually very easy to make a timer. All we have to do is turn the code above into a function, set up a setTimeout command, and create a html division somewhere on the page to hold our timer. Here's the new code!

<!-- This span is where the countdown timer will appear -->
<div id='countdown'></div>

<script type="text/javascript">
// Here's our countdown function.
function happyNewYear() {
   var now = new Date();
   var newYear = new Date('January 1, '+(now.getFullYear()+1));
   var diff=newYear-now;
   var milliseconds=Math.floor(diff % 1000);   
       diff=diff/1000;            
   var seconds=Math.floor(diff % 60);
       diff=diff/60;
   var minutes=Math.floor(diff % 60);
       diff=diff/60;
   var hours=Math.floor(diff % 24);
       diff=diff/24;
   var days=Math.floor(diff);
   
   // We'll build a display string instead of doing document.writeln
   var outStr = days + ' days, ' + hours+ ' hours, ' + minutes;
       outStr+= ' minutes, ' + seconds + ' seconds until the new year!'; 

   // Insert our display string into the countdown span.
   document.getElementById('countdown').innerHTML=outStr;

   // call this function again in exactly 1 second.   
   setTimeout("happyNewYear()",1000);
}

// call the countdown function (will start the timer)
happyNewYear();   
</script>

When the function is called (every second), now is always set to the current, ever advancing date, while the newYear always remains a constant. So the function works to countdown the passing time to the destination date (new year).

And here's the result!

Does the time appear a bit off? Maybe because right now you're in Daylight time and the new year is in daylight savings time! If this is the case, once everyone falls back the timer will again be in sync with your expectations!

Making A Clock

Making a clock is very similar to making a countdown timer. All we have to do is to create a new date and get it's hours, minutes, and seconds.

<!-- This span is where the clock will appear -->
<div id='clockDiv'></div>

<script type="text/javascript">
function clock() {
   var now = new Date();
   var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
   document.getElementById('clockDiv').innerHTML=outStr;
   setTimeout('clock()',1000);
}
clock();
</script>

And the result (in military time):

Getting The Number Of Days In A Month

Javascript has a little quirk where a date of zero will set the date to be the last day of the previous month. Likewise is there are 30 days in a month and you set a date of 31 it will be the 1st day of the next month, a date of 40 would be the 10th day of the next month. This can lead to some very weird funkiness if you're not careful but we can definitely exploit this for a useful prototype which will give us the number of days in a specific month. We'll do this up as a prototype so it's available to all our Dates.

Date.prototype.daysInMonth = function () {
   return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}

var d = new Date();
document.writeln('Number of days in this month: '+d.daysInMonth());

And the result (live!):

Getting The Name Of The Day And Month

While the Javascript Date Object has many useful features, one glaring oversight is that when you ask it for the day or month it will return only the numerical representation. This is easy enough to fix with prototypes however.

Date.prototype.getDayName = function(shortName) {
   var Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
   if (shortName) {
      return Days[this.getDay()].substr(0,3);
   } else {
      return Days[this.getDay()];
   }
}

Date.prototype.getMonthName = function() {
   return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][this.getMonth()]; 
}

These two methods are pretty simple to use. If you want the month name just do…

var d = new Date();
month = d.getMonthName();

If you want the name of the day, do…

var d = new Date();
day = d.getDayName();

If you'd like the three character day name (mon/tue/wed, etc) then pass an argument to getDayName. As long as the argument isn't false, null or any other falsey value the name will be shortened to its three letter equivalent.

var d = new Date();
day = d.getDayName(true);

Making a Calendar

Making a calendar is a bit more complex than making a timer or clock but mostly because any calendar script is going to be generating HTML to display the calendar and whenever you have programs writing programs things always get a bit funky! We'll do this as a prototype so all you have to do is create a date with the month you want the calendar for and use the .calendar() method.

Note this prototype assumes you've included the getMonthName() and daysInMonth() prototypes described above, the calendar will break if they are not included in your code.

Date.prototype.getMonthName = function() {
   return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][this.getMonth()]; 
}

Date.prototype.daysInMonth = function () {
   return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}

Date.prototype.calendar = function() {

   // The number of days in the month.
   var numDays = this.daysInMonth();
   // Get the starting day of this calendar, mon, tue, wed, etc.
   var startDay= new Date(this.getFullYear(), this.getMonth(), 1).getDay();
   
   // We'll build our table in the buildStr variable then pass what we build back.
   // This will be a HTML table -- Build the header rows...
   var buildStr ='<table summary="Calendar" class="calendar" style="text-align: center">';
   buildStr+='<tr><td colspan=7>'+this.getMonthName()+' '+this.getFullYear()+'</td></tr>';
   buildStr+='<tr><td>Sun</td><td>Mon</td><td>Tue</td>';
   buildStr+='<td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td></tr>';
   buildStr+='<tr>';
   
   // Create blank boxes until we get to the day which actually starts the month
   for(var i=0; i<startDay; i++) {
      buildStr+='<td>&nbsp;</td>';
   }
   
   // Border is a counter, initialize it with the number of "blank" days at the
   // start of the calendar.  Now each time we add a new date we'll do a modulus
   // 7 and check for 0 (remainder of border/7 = 0), if it's zero it's time to
   // make a new row.
   var border=startDay;
   
   // For each day in the month, insert it into the calendar.
   for(i=1; i<=numDays; i++) {
      buildStr+='<td>'+i+'</td>';
      border++;
      if (((border%7)==0)&&(i<numDays)) {
         // Time to start a new row, if there are any days left.
         buildStr+='</tr><tr>';
      }
   }
   
   // All the days have been used up, so just pad empty days until the
   // end of the calendar.
   while((border++%7)!=0) {
      buildStr+='<td>&nbsp;</td>';
   }
   
   // Finish the table.
   buildStr+='</tr>';
   buildStr+='</table>';
   
   // return it.
   return buildStr;
}

d=new Date("June 1, 2007");
document.writeln(d.calendar());

And the result (with a little DHTML extra thrown in)…



Javascript Dates Are Passed By Reference

When you pass a date to a function, the date is passed as a pointer to the original value. This means that any changes you make to the date inside the function affect the original Date.

var originalDate = new Date('January 1, 1970');

function changeYear(passedDate) {
  passedDate.setFullYear(1980);
}


changeYear(originalDate);
document.writeln(originalDate.getFullYear()); // Outputs 1980, not 1970!

Javascript Dates Are Assigned By Reference

When you assign a variable an existing date Object, you are assigning a pointer to the original Date. Anything you do to the new variable affects the original.

var originalDate = new Date('January 1, 1970');
var newDate = originalDate;

newDate.setFullYear(1980);

document.writeln(originalDate.getFullYear()); // Outputs 1980, not 1970!

Understanding Time Zones

UTC, or Coordinated Universal Time, is, for all intended purposes, Greenwich Mean Time, or the timezone of Greenwich, England. EST (US East coast) is -5 hours from GMT, CST (central US) is -6 hours from GMT, MST (Mountain Time) is -7 hours and PST (central time) is -8 hours, although these numbers can vary by as much as an hour depending on whether or not Daylight Savings Time is in effect or not.

When you create a new date, without specifying a time zone, Javascript will create the date using the browser's timezone. When you output a date, unless you specifically use UTC date methods, the date will be converted to the user's local timezone regardless of how the date was created. For instance if you created a date in the Eastern timezone, the date/time will be converted to pacific time if that is where the user resides.

Wherever you see UTC, in a Javascript method, it's safe to read it as GMT (Greenwich Mean Time).

Javascript understands the continental US timezone abbreviations in addition to GMT and UTC which are equivalent. If you need a non-US/GMT/UTC timezone specify GMT+hhmm where hh=hour and mm=minutes of the offset where positive numbers are west of Greenwich to Japan, and negative numbers are east of Greenwich to Japan. For instance GMT+0530 would be an offset of 5 hours, 30 minutes.

American timezone's first letter stand for the geographical region.

  • E - Eastern
  • C - Central
  • M - Mountain
  • P - Pacific

The middle letter can be either D for daylight time (spring forward), or S for daylight savings time (fall back). The last letter is always T for timezone. So EST would be eastern daylight savings time, PDT would be Pacific Daylight Time.

If you are encountering problems with timezones and are using United States Timezones check the middle letter and make sure you are using daylight[savings] time properly.

Date Method Reference

The following methods are a part of the Date object. As you move the mouse over each row it will be highlighted to make it easier to read the table. If you click on a method you will be taken to that method's detailed instructions.

MethodIE VersionMozilla VersionNotes
getDate3.02.0Returns the Date: 12/15/2006
getDay3.02.0Returns the Day (0=sunday, 1=monday,etc)
getFullYear5.04.5Returns the 4 digit year
getHours3.02.0Returns the hour in millitary time (0-23)
getMilliseconds5.04.5Returns the milliseconds
getMinutes3.02.0Returns the minutes (0-59)
getMonth3.02.0Returns the month (0=Jan, 1=Feb, etc)
getSeconds3.02.0Returns the seconds (0-59)
getTime3.02.0# of milliseconds since 1/1/1970
getTimezoneOffset3.02.0Returns the offset from GMT
getUTCDate5.04.5Returns the Date as a UTC date.
getUTCDay5.04.5Returns the Day as a UTC day.
getUTCFullYear5.04.5Returns the UTC 4 digit year
getUTCHours5.04.5Returns the UTC Hours
getUTCMilliseconds5.04.5Returns the UTC Milliseconds
getUTCMinutes5.04.5Returns the UTC Minutes
getUTCMonth5.04.5Returns the UTC Month
getUTCSeconds5.04.5Returns the UTC Seconds
getVarDate4.0---dates for com/activeX object
getYear3.02.0Deprecated. Use getFullYear()
now---???Static-Returns the current timestamp.
parse3.02.0Static-Parses a date returning a timestamp.
setDate3.02.0Sets the date of the month
setFullYear5.04.5Sets the 4 digit year
setHours3.02.0Sets the Hour
setMilliseconds3.02.0Sets the Milliseconds
setMinutes3.02.0Sets the Minutes
setMonth3.02.0Sets the month.
setSeconds3.02.0Sets the seconds.
setTime3.03.0Sets date by timestamp.
setUTCDate5.04.5Sets Date, GMT Timezone.
setUTCFullYear5.04.5Sets 4 digit Year, GMT Timezone.
setUTCHours5.04.5Sets Hours, GMT Timezone.
setUTCMilliseconds5.04.5Sets milliseconds, GMT Timezone.
setUTCMinutes5.04.5Sets Minutes, GMT Timezone.
setUTCMonth5.04.5Sets Month, GMT Timezone.
setUTCSeconds5.04.5Sets Seconds, GMT Timezone.
setYear3.02.0Deprecated. Use setFullYear()
toDateString5.5???Outputs the date (no time/timezone) as a string.
toGMTString3.03.0Outputs the date adjusted to GMT.
toLocaleDateString3.02.0Outputs the date using the current locale's conventions.
toLocaleString3.02.0Outputs only the date as a localized string.
toLocaleTimeString3.02.0Outputs only the time as a localized string.
toSource---4.5Returns the date "source code"
toString3.03.0Outputs the date as a string
toTimeString3.03.0Returns the time as a string.
toUTCString5.04.5Returns the date as a GMT string.
UTC3.02.0Static-Returns the Date as a UTC timestamp
valueOf3.02.0See toString()

??? - Unofficially supported by firefox but not documented so no version support information is available.
--- - Not supported.

Date.getDate()

The getDate() method returns the date of the object adjusted to the user's timezone. See also getUTCDate for an unadjusted date.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getDate()); // Outputs 23

Supported since IE 3.0, Netscape 2.0.

Date.getDay()

This method returns the day as a number where 0=sunday, 1=monday, 2=tuesday, 3=wednesday, 4=thursday, 5=friday, 6=saturday. The number is adjusted to the browser's timezone. See also getUTCDay for an unadjusted day.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getDay()); // Outputs 6 for Saturday

Supported since IE 3.0, Netscape 2.0.

Date.getFullYear()

With y2k rapidly approaching, the browser makers created this method to give Javascript the ability to handle 4 digit years. For compatibility reasons getYear() and setYear() remain but should never be used. This result is adjusted to the browser's timezone. See also getUTCGetFullYear for an unadjusted year.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getFullYear()); // Outputs 1993

Supported since IE 5.0, Netscape 4.5.

Date.getHours()

This method returns the hour represented by the date. The time is adjusted to the user's timezone. See also getUTCHours() for an unadjusted time.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getHours()); // Outputs 1993

Supported since IE 3.0, Netscape 2.0.

Date.getMilliseconds()

This method returns the milliseconds represented by the date. The time is adjusted to the user's timezone. See also getUTCMilliseconds() for an unadjusted time.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getMilliseconds()); // Outputs 000

Supported since IE 3.0, Netscape 2.0.

Date.getMinutes()

This method returns the minutes represented by the date. The time is adjusted to the user's timezone. See also getUTCMinutes() for an unadjusted time.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getMinutes()); // Outputs 57

Supported since IE 3.0, Netscape 2.0.

Date.getMonth()

This method returns the month of the date represented as an integer between zero and 11 where 0=January, 1=February, 2=March, 3=April, 4=May, 5=June, 6=July, 7=August, 8=September, 9=October, 10=November, 11=December. The time is adjusted to the user's timezone. See also getUTCMonth() for an unadjusted time.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getMinutes()); // Outputs 9 (October)

Supported since IE 3.0, Netscape 2.0.

Date.getSeconds()

This method returns the seconds represented by the date. The time is adjusted to the user's timezone. See also getUTCSeconds() for an unadjusted time.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getSeconds()); // Outputs 14

Supported since IE 3.0, Netscape 2.0.

Date.getTime()

This method returns an integer representing the number of seconds that have elapsed since January 1, 1970 GMT and the Date represented by the object. This value is equal to the timezone used to create the date (if no timezone was specified the timezone being used by the browser's computer is used). This method is very useful for creating uniqe stamps timestamps and is frequently appeneded to the end of URL's for AJAX calls to make sure the URL is unique and not cached by Internet Explorer.

var d = new Date('October 23, 1993 6:57:14 am');
document.writeln(d.getTime()); // Outputs 751,377,434,000

Supported since IE 3.0, Netscape 2.0.

Date.getTimezoneOffset()

This method returns an integer representing the number of Minutes the date has been offset from GMT (Divide by 60 to get the number of hours). This number can vary as your area moves in and out of daylight savings time. The number returned is negative east of Greenwich to Japan, and positive to the west to Japan. Which means New York will return 5 hours instead of -5.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getTimezoneOffset()); // Outputs 300 (5 hours).

Supported since IE 3.0, Netscape 2.0.

Date.getUTCDate()

This method returns the date adjusted to Greenwich Mean Time. While it may seem that a date wouldn't be affected by UTC/GMT, if the time is close enough for midnight for the timezone to shift the UTC/GMT into another day/month/year, this method will return the correctly adjusted date.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCDate()); // Outputs 23

Supported since IE 5.0, Netscape 4.5.

Date.getUTCDay()

This method returns the day adjusted to Greenwich Mean Time. While it may seem that a date wouldn't be affected by UTC/GMT, if the time is close enough for midnight for the timezone to shift the UTC/GMT into another day/month/year, this method will return the correctly adjusted day.

The return value is an integer from zero to six where 0=Sunday, 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCDay()); // Outputs 6 (Saturday)

Supported since IE 5.0, Netscape 4.5.

Date.getUTCFullYear()

This method returns the 4 digit year adjusted to Greenwich Mean Time. While it may seem that a date wouldn't be affected by UTC/GMT, if the time is close enough for midnight for the timezone to shift the UTC/GMT into another day/month/year, this method will return the correctly adjusted day.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCFullYear()); // Outputs 1993

Supported since IE 5.0, Netscape 4.5.

Date.getUTCHours()

This method returns the current hour (0-59) adjusted to Greenwich Mean Time.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCFullYear()); // Outputs 11

Supported since IE 5.0, Netscape 4.5.

Date.getUTCMilliseconds()

This method returns the current Milliseconds adjusted to Greenwich Mean Time. In practice since GMT offsets only affect hours and minutes there is no difference between the value returned by this method and the value returned by getMilliseconds()

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCMilliseconds()); // Outputs 0

Supported since IE 5.0, Netscape 4.5.

Date.getUTCMinutes()

This method returns the current minutes (0-59) adjusted to Greenwich Mean Time.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCMinutes()); // Outputs 57

Supported since IE 5.0, Netscape 4.5.

Date.getUTCMonth()

This method returns an integer representing the month adjusted to Greenwich Mean Time. While it may seem that a date wouldn't be affected by UTC/GMT, if the time is close enough for midnight for the timezone to shift the UTC/GMT into another day/month/year, this method will return the correctly adjusted month. This method returns a number from 0-11 where 0=January, 1=February, 2=March, 3=April, 4=May, 5=June, 6=July, 7=August, 8=September, 9=October, 10=November, 11=December.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCMonth()); // Outputs 9

Supported since IE 5.0, Netscape 4.5.

Date.getUTCSeconds()

This method returns the current seconds adjusted to Greenwich Mean Time. In practice since GMT offsets only affect hours and minutes there is no difference between the value returned by this method and the value returned by getSeconds()

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getUTCSeconds()); // Outputs 14

Supported since IE 5.0, Netscape 4.5.

Date.getVarDate()

From the IE Documentation: The getVarDate method is used when interacting with COM objects, ActiveX® objects or other objects that accept and return date values in VT_DATE format, such as Visual Basic and VBScript. The actual format is dependent on regional settings and should not be replied upon within JScript.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getVarDate()); // Outputs Sat Oct 23 06:57:14 CDT 1993

Supported since IE 5.0, not supported elsewhere.

Date.getYear()

Deprecated! This method remains only for backward compatability with older scripts. getYear() returns the year-1900 which in the 1900's returned the last two digits of the date, and caused everyone to get all panicky about y2k stuff. It still works in Javascript, but should not be used.

var d = new Date('October 23, 1993 6:57:14 am EST');
document.writeln(d.getYear()); // Outputs 93

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.getYear()); // Outputs 106

Supported since IE 3.0, Netscape 2.0.

Date.now()

This method is listed in the firefox documentation without details. It is not supported by other browsers. This is a static method, you do not need to create a new Date object to use it, merely address it as Date.now().

This method returns the current timestamp -- IE how many milliseconds have elapsed since January 1, 1970 to the present.

var timestamp = Date.now();  // timestamp = ~751,377,434,000 

Supported Firefox, not supported elsewhere.

Date.parse(dateString)

This is a static method which means you can use it without creating a new Date object. When called, this method will attempt to parse the dateString and turn it into a timestamp (number of elapsed seconds since January 1, 1970). If the parser is unable to do this it will return NaN (not a number), indicating a failure.

document.writeln(Date.parse('Failure!')); // Outputs NaN
document.writeln(Date.parse('October 23, 2006 6:57:14 am EST')); // Outputs: 1,161,604,634,000

Supported since IE 3.0, Netscape 2.0.

Date.setDate(date)

This method sets the date of the object based on the integer you pass. A zero will adjust the Date object to be the last day of the previous month, negative numbers will move the date back further. Numbers higher than the end of the current month will adjust the month forward into the next month (or months if you use very large numbers). So If you try to set February 30 you will actually be setting March 1st or 2nd depending on leap years. Passing a string or another unexpected value will set the date equal to the value of "Invalid Date". This date is set according to the user's timezone.

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setDate(10);
document.writeln(d); // Outputs: Tue Oct 10 2006 06:57:14

Supported since IE 3.0, Netscape 2.0.

Date.setFullYear(FourDigitYear)

This method sets the year to the 4 digit year you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setFullYear(1996);
document.writeln(d); // Outputs: Tue Oct 10 1996 06:57:14

Supported since IE 5.0, Netscape 4.5.

Date.setHours(Hours)

This method sets the time of the Date object to the hours you pass. The hours are assumed to be in the browser's timezone. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setHours(4);
document.writeln(d); // Outputs: Tue Oct 10 2006 04:57:14

Supported since IE 5.0, Netscape 4.5.

Date.setMilliseconds(Milliseconds)

This method sets the Milliseconds of the Date object to the value you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setMilliseconds(450);
document.writeln(d.getTime()); // Outputs: 1161604634450

Supported since IE 3.0, Netscape 2.0.

Date.setMinutes(Minutes)

This method sets the Minutes of the Date object to the value you pass. The minutes are assumed to be in the browser's timezone. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setMinutes(15);
document.writeln(d); // Outputs: Tue Oct 10 2006 06:15:14

Supported since IE 3.0, Netscape 2.0.

Date.setMonth(Month)

This method sets the Month of the Date object to the value you pass. Month must be an integer between 0 and 11 where 0=January, 1=February, 2=March, 3=April, 4=May, 5=June, 6=July, 7=August, 8=September, 9=October, 10=November, 11=December. Passing an invalid or unexpected value will result in the Date being set to "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setMonth(1);
document.writeln(d); // Outputs: Tue Feb 10 2006 06:15:14

Supported since IE 3.0, Netscape 2.0.

Date.setSeconds(Seconds)

This method sets the seconds of the Date object to the value you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setSeconds(45);
document.writeln(d); // Outputs: Tue Oct 10 2006 04:57:45

Supported since IE 3.0, Netscape 2.0.

Date.setTime(timestamp)

This method accepts a timestamp (representing the number of milliseconds since the January 1, 1970 epoch) and sets the date according to that number. If you used Date.getTime() to save a timestamp in your database you can load that timestamp back into a Date object with this method. Passing an invalid or unexpected value will result in the value of the Date being set to "Invalid Date".

var d = new Date();
d.setTime(1161604634450);
document.writeln(d); // Outputs: October 23, 2006 6:57:14

Supported since IE 3.0, Netscape 2.0.

Date.setUTCDate(date)

This method sets the date of the object based on the integer you pass. A zero will adjust the Date object to be the last day of the previous month, negative numbers will move the date back further. Numbers higher than the end of the current month will adjust the month forward into the next month (or months if you use very large numbers). So If you try to set February 30 you will actually be setting March 1st or 2nd depending on leap years. Passing a string or another unexpected value will set the date equal to the value of "Invalid Date". This date is set according to the GMT/UTC timezone.

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCDate(10);
document.writeln(d); // Outputs: Tue Oct 10 2006 06:57:14

Supported since IE 5.0, Netscape 4.5.

Date.setUTCFullYear(FourDigitYear)

This method sets the year to the 4 digit year you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCDFullYear(1996);
document.writeln(d); // Outputs: Tue Oct 10 1996 06:57:14

Supported since IE 5.0, Netscape 4.5.

Date.setUTCHours(Hours)

This method sets the time of the Date object to the hours you pass. The hours are set to the GMT/UTC timezone. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCHours(4);
document.writeln(d); // Outputs: Sun Oct 22 2006 23:57:14 

Supported since IE 5.0, Netscape 4.5.

Date.setUTCMilliseconds(Milliseconds)

This method sets the Milliseconds of the Date object to the value you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCMilliseconds(450);
document.writeln(d.getTime()); // Outputs: 1161604634450

Supported since IE 5.0, Netscape 4.5.

Date.setUTCMinutes(Minutes)

This method sets the Minutes of the Date object to the value you pass. The minutes are set to be UTC/GMT. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCMinutes(15);
document.writeln(d); // Outputs: Tue Oct 10 2006 06:15:14

Supported since IE 5.0, Netscape 4.5.

Date.setUTCMonth(Month)

This method sets the Month of the Date object to the value you pass. Month must be an integer between 0 and 11 where 0=January, 1=February, 2=March, 3=April, 4=May, 5=June, 6=July, 7=August, 8=September, 9=October, 10=November, 11=December. Passing an invalid or unexpected value will result in the Date being set to "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCMonth(1);
document.writeln(d); // Outputs: Tue Feb 10 2006 06:15:14

Supported since IE 5.0, Netscape 4.5.

Date.setUTCSeconds(Seconds)

This method sets the seconds of the Date object to the value you pass. Passing a string or other unexpected value sets the Date object equal to the value "Invalid Date".

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setUTCSeconds(45);
document.writeln(d); // Outputs: Tue Oct 10 2006 04:57:45

Supported since IE 5.0, Netscape 4.5.

Date.setYear(year)

Deprecated! Use Date.setFullYear(yyyy). This method exists for backwards compatibility only. If the value of year is a number between 0 and 99 then that number is added to 1900, otherwise the value of year is used as the full year. This method is no longer in use.

var d = new Date('October 23, 2006 6:57:14 am EST');
d.setYear(95);
document.writeln(d); // Outputs: Tue Oct 10 1995 04:57:45

Supported since IE 3.0, Netscape 2.0.

Date.toGMTString()

Deprecated! Use Date.toUTCString(). There's no difference between toUTCString and to GMTString but GMT is this qauint english town with lots of history and stuff and UTC is COORDINATED UNIVERSAL TIME and is all about atomic clocks and scientists and stuff. So don't use toGMTString().

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toGMTString()); // Outputs: Mon, 23 Oct 2006 11:57:14 GMT
document.writeln(d.toUTCString()); // Outputs: Mon, 23 Oct 2006 11:57:14 GMT 

Supported since IE 3.0, Netscape 2.0.

Date.toLocaleDateString()

If you're going to output a date string, the toLocale methods are by far the best. They attempt to convert the string to conventions used in the native country of the browser, so if you have a date set in EST and a visitor from China is on your site he or she may actually see the Date in a way that's meaningful to them even if everything else on the page is gibberish.

This method returns only the date portion of the Date.

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toLocaleDateString()); // Outputs: Monday, October 23, 2006

Supported since IE 3.0, Netscape 2.0.

Date.toLocaleString()

If you're going to output a date string, the toLocale methods are by far the best. They attempt to convert the string to conventions used in the native country of the browser, so if you have a date set in EST and a visitor from China is on your site he or she may actually see the Date in a way that's meaningful to them even if everything else on the page is gibberish.

This method returns both the time and date.

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toLocaleString()); // Outputs: Monday, October 23, 2006 6:57:14 AM

Supported since IE 3.0, Netscape 2.0.

Date.toLocaleTimeString()

If you're going to output a date string, the toLocale methods are by far the best. They attempt to convert the string to conventions used in the native country of the browser, so if you have a date set in EST and a visitor from China is on your site he or she may actually see the Date in a way that's meaningful to them even if everything else on the page is gibberish.

This method returns only the time..

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toLocaleTimeString()); // Outputs: 6:57:14 AM

Supported since IE 3.0, Netscape 2.0.

Date.toSource()

All Firefox objects have a toSource() method. It attempts build up a "source code" version of the data the object contains. It does this in such a way that if you pass the result back to the object's constructor the object will be perfectly reconstructed. It has it's greatest uses in turning objects {} into JSON structures for transport.

This method is not supported outside of Firefox. It will cause errors in other browsers.

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toSource()); // Outputs: (new Date(1161604634000))

Supported since Netscape 4.5. Not supported elsewhere.

Date.toString()

Outputs, as a string, the date, time, and timezone represented by the Date object. The output is converted into the user's timezone if the creation date used a different timezone.

The output below is static, your result will be different if you're in a different timezone. Note also the time is identical even though we created the timezone in the eastern timezone and the output was generated in the central timezone. The reason for this is that EST is eastern daylight saving times and central daylight time is not daylight savings time.

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toString()); 
// Outputs: Mon Oct 23 2006 06:57:14 GMT-0500 (Central Daylight Time)

Supported since IE 3.0, Netscape 2.0.

Date.toUTCString()

You're supposed to use this instead of toGMTString() even though it outputs a string specifying that the time/date is GMT. It's silly, but there you go. There's no difference between toUTCString and toGMTString save that toGMTString has been deprecated.

var d = new Date('October 23, 2006 6:57:14 am EST');
document.writeln(d.toGMTString()); // Outputs: Mon, 23 Oct 2006 11:57:14 GMT
document.writeln(d.toUTCString()); // Outputs: Mon, 23 Oct 2006 11:57:14 GMT 

Supported since IE 3.0, Netscape 2.0.

Date.UTC(year, month[, date[, hours[, min[, sec[, ms]]]]])

This is a static method meaning you don't have to create a new Date object to use it. This is similar to Date.parse(string) except it accepts the data as arguments. If it could construct a valid date it will return a timestamp representing the number of elapsed milliseconds since January 1, 1970.

This differs from the Date constructor in that the timestamp returned represents a GMT/UTC date. Passing parameters to the Date constructor results in a timestamp representing the timezone of the browser.

Be mindful that the month ranges from 0-11, not 1-12.

var d = new Date(Date.UTC(2006, 9, 23, 6, 57, 14));
document.writeln(d.toUTCString()); // Outputs: Mon, 23 Oct 2006 06:57:14 GMT
document.writeln(d.toString()); 
// Outputs: Mon Oct 23 2006 01:57:14 GMT-0500 (Central Daylight Time)

Supported since IE 5.0, Netscape 4.5.

Date.valueOf()

See Date.toString();

Supported since IE 3.0, Netscape 2.0.