MSDN Library

Date and Time Calculations (JavaScript)

The JavaScript Date object and related methods are used to perform common calendar and clock tasks, such as manipulating and comparing dates, and calculating elapsed time.

When you create an instance of the Date object, it contains a value representing a particular instant in time, accurate to a millisecond. You can then read or change this date and time value.

The following example shows how to obtain the current date and display it in the format mm/dd/yy.

// Create a date object. Because no arguments are
// passed, the date object contains the current date and
// time (to the millisecond).
var dt = new Date();

// Determine and display the month, day, and year.
// The getMonth method uses a zero offset for
// the month number.
var month = dt.getMonth()+1;
var day = dt.getDate();
var year = dt.getFullYear();
alert(month + '/' + day + '/' + year);

In the following example, a specific date is passed to the constructor.

// Create a date object for a specific date.
var dt = new Date('8/24/2009');

JavaScript is fairly flexible about the date format. It allows for variants such as 8-24-2009, August 24, 2009, and 24 Aug 2009. For more information, see Formatting Date and Time Strings (JavaScript).

You can also specify a time, as shown in the following examples.

// Create a date object for a specific date and time.
// The time format is hours:minutes:seconds.
var dtA = new Date('8/24/2009 14:52:10');

// Create a date object for the same date and time as in
// the previous example.
// The parameters are:
// year, month, day, hours, minutes, seconds.
// August is month 7 because January is month 0.
var dtB = new Date(2009, 7, 24, 14, 52, 10);

A previous example uses the getMonth, getDate and getFullYear methods to obtain parts of the date. An equivalent group of set methods enables you to change the value in the Date object.

The following example shows how you can set a date to yesterday's date. It obtains today's date and day of the month, and then sets the day to one day earlier by using the setDate method.

// Get today's date and day of month.
var myDate = new Date();
var dayOfMonth = myDate.getDate();

// Reset myDate to one day earlier.
myDate.setDate(dayOfMonth - 1);

JavaScript increments to the next month or year as required. For example, if today is the 28th of January and you add 7 days, it correctly sets the date to February 4. The following example adds one week to the current date. The example also clears the time from the date.

var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);

// Clear the time.
myDate.setHours(0, 0, 0, 0);

The following example contains a loop that outputs dates starting with 1 month from today. The months increment correctly to the next year.

var currentDate = new Date();

for(var index = 1; index <= 12; index++)
    var myDate = new Date();
    myDate.setMonth(currentDate.getMonth() + index);

    document.write ("Month+" + index + ": ");
    document.write (myDate);
    document.write ("<br />");

The following example obtains the date that is one year before today.

var myDate = new Date();
myDate.setFullYear (myDate.getFullYear() - 1);

The following example obtains the first day of the month that follows the current month. It increments the month and then sets the day of the month to 1.

function GetFirstOfNextMonth()
    var myDate = new Date();
    myDate.setMonth(myDate.getMonth() + 1);

    return myDate;

The following example determines the last day of the current month. To do this, it determines the first of the following month, and then subtracts a day.

// Determine the last day of the current month.
// The GetFirstOfNextMonth() function is in the previous example.
var myDate = GetFirstOfNextMonth();
myDate.setDate (myDate.getDate() - 1);

The getDay method (not to be confused with getDate) returns a value between 0 and 6 to indicate the day of the week. Sunday is zero, Monday is 1, and so on. The following example shows how to determine the current day of the week.

var arDays = new Array("Sunday", "Monday", "Tuesday",
    "Wednesday", "Thursday", "Friday", "Saturday");

var today = new Date();
var dayNum = today.getDay();
var dayOfWeek = arDays[dayNum];

The following example returns the date of the Friday before the current date.

function getPreviousDayOfWeek(dayOfWeekNum)
    var dt = new Date();
    if (dt.getDay() == dayOfWeekNum)
        // It is currently the day of the week specified in
        // the function call. Subtract one week.
        dt.setDate(dt.getDate() - 7);
        // Go back a day at a time until arriving
        // at the specified day of week.
        while (dt.getDay() != dayOfWeekNum)
            dt.setDate(dt.getDate() - 1);

    return dt;

var friday = 5;
var myDate = getPreviousDayOfWeek(friday);

The following example determines the date for the U.S. holiday Thanksgiving, which is defined as the fourth Thursday in November. The script finds November 1 of the current year, then finds the first Thursday, and then adds three weeks.

// Determine the current date and clear the time.
var myDate = new Date();
myDate.setHours(0, 0, 0, 0);

// Determine November 1 of the current year.
var november = 10;

// Find Thursday.
var thursday = 4;
while(myDate.getDay() != thursday)
    myDate.setDate(myDate.getDate() + 1) ;

// Add 3 weeks.
myDate.setDate(myDate.getDate() + 21);

The getTime method returns the number of milliseconds that have elapsed since the zero date and time of midnight on January 1, 1970. For a date before that date, getTime returns a negative number.

You can use getTime to set a start and end time for calculating an elapsed time. It can be used for measuring small units, such as a few seconds, and large units, such as days.

Determining Elapsed Time in Seconds

This example calculates elapsed time in seconds. It works regardless of how long the interval is. The milliseconds reported by the getTime method are an absolute value from the zero date. Therefore, they keep moving forward through changes in the minute, hour, and day.

var startTime = new Date();
prompt("What is your name?","");
var endTime = new Date();
var elapsed = (endTime.getTime() - startTime.getTime()) / 1000; 
alert("You took " + elapsed + " seconds to type your name.");

Determining Elapsed Time in Days

To work with more manageable units, you can divide the milliseconds provided by the getTime method by an appropriate number. For instance, to turn milliseconds into days, divide the number by 86,400,000 (1000 x 60 x 60 x 24).

The following example shows how much time has elapsed since the first day of the current year. It uses a succession of division operations to calculate elapsed time in days, hours, minutes, and seconds. It does not account for daylight savings time.

// Set the unit values in milliseconds.
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;

// Determine the current date and time.
var today = new Date();

// Determine January 1, at midnight, of the current year.
var january = 0;
var startOfYear = new Date();
startOfYear.setHours(0, 0, 0, 0);

// Determine the difference in milliseconds.
var interval = today.getTime() - startOfYear.getTime();

// Calculate how many days the interval contains. Subtract that
// many days from the interval to determine the remainder.
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );

// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );

var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );

var seconds = Math.floor(interval / 1000 );

// Display the result.
var msg = days + " days, " + hours + " hours, "
 + minutes + " minutes, " + seconds + " seconds.";

Determining the User's Age

The following example determines the user's age in years. It subtracts the birth year from the current year, and then subtracts 1 if the birthday has not occurred yet in the current year. It does not use elapsed milliseconds, because our definition of age is not based on a strict interval.

var birthday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - birthday.getFullYear();

// Reset birthday to the current year.

// If the user's birthday has not occurred yet this year, subtract 1.
if (today < birthday)
alert("You are " + years + " years old.");

You need to be careful when comparing dates to be sure that you are doing it correctly. You can learn more about that in the next section of this topic.

The following example shows one method of calculating the user's age in months. The script includes a test to determine whether the birthday has occurred in the current month.

var birthday = new Date("8/1/1985");
var today = new Date();
var years = today.getFullYear() - birthday.getFullYear();

// Determine the number of months.
var months = (years * 12) + (today.getMonth() - birthday.getMonth());

// Adjust the months if the birthday has not occurred yet in the current month.
if (today.getDate() < birthday.getDate())
alert("You are " + months + " months old.");

In JavaScript, if you are comparing objects by using greater than or less than (<, >, <=, or >=), the values of the objects are evaluated before the comparison is performed. Equality comparisons work differently. For the == operator, the comparison returns true only if both sides of the operator refer to the same object. The != operator operates similarly.

The getTime method returns the number of milliseconds between midnight, January 1, 1970 and the time value in the Date object. It enables you to compare the millisecond representations of two dates.

A millisecond-based date comparison however, does not work correctly if one of the Date objects contains a time other than midnight.

If you create a Date object without including a constructor argument, the time associated with the date is the current time. If you create a Date object for a specific date, the time associated with the date is midnight at the start of that day.

The following example checks whether the current date is the same as a specified date. To set the current date in todayAtMidn, the script creates a Date object for the current year, month, and day.

// Determine the current date and time, and then
// determine the current date at midnight.
var now = new Date(); 
var todayAtMidn = new Date(now.getFullYear(), now.getMonth(), now.getDate());

// Set specificDate to a specified date at midnight.
var specificDate = new Date("9/21/2009");

// Compare the two dates by comparing the millisecond
// representations.
if (todayAtMidn.getTime() == specificDate.getTime())
© 2016 Microsoft