Date and Time Calculations

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

Setting a Date to the Current Date

When you create an instance of the Date Object, it contains a value that represents 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 : Date = new Date();

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

print (month + "/" + day + "/" + year);

Setting a Specific Date

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

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

JScript is fairly flexible about the date format. It allows for variants such as 8-24-2009, August 24, 2009, and 24 Aug 2009.

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 : Date = 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 : Date = new Date(2009, 7, 24, 14, 52, 10);

Adding and Subtracting Days

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 the previous day's date. It obtains the current day's date and day of the month, and then sets the day to one day earlier by using the setDate Method.

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

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

JScript increments to the next month or year as required. For example, if the current date 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 : Date = new Date();
myDate.setDate(myDate.getDate() + 7);

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

Working with Months and Years

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

var currentDate : Date = new Date();

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

    print ("Month+" + index + ": " + myDate);
}

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

var myDate : Date = 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() : Date
{
    var myDate : Date = new Date();
    myDate.setMonth(myDate.getMonth() + 1);
    myDate.setDate(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 : Date = GetFirstOfNextMonth();
myDate.setDate (myDate.getDate() - 1);

Working with Days of the Week

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 : Array = ["Sunday", "Monday", "Tuesday",
    "Wednesday", "Thursday", "Friday", "Saturday"];

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

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

function getPreviousDayOfWeek(dayOfWeekNum : Number) : Date
{
    var dt : Date = 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);
    }
    else
    {
        // 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 : Number = 5;
var myDate : Date = 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 : Date = new Date();
myDate.setHours(0, 0, 0, 0);

// Determine November 1 of the current year.
var november : Number = 10;
myDate.setMonth(november);
myDate.setDate(1);

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

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

Calculating Elapsed Time

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 increasing through changes in the minute, hour, and day.

Console.Write("What is your name? ");

var startTime : Date = new Date();
var name : String = Console.ReadLine();
var endTime : Date = new Date();

var elapsed : Number = 
    (endTime.getTime() - startTime.getTime()) / 1000; 

Console.WriteLine("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 : Number = 1000 * 60;
var msecPerHour : Number = msecPerMinute * 60;
var msecPerDay : Number = msecPerHour * 24;

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

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

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

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

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

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

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

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

print(msg);

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 : Date = new Date("8/1/1985");
var today : Date = new Date();
var years : Number = today.getFullYear() - birthday.getFullYear();

// Reset birthday to the current year.
birthday.setFullYear(today.getFullYear());

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

Note

You must be careful when comparing dates to make 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 user's birthday has occurred in the current month.

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

// Determine the number of months.
var months : Number = (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())
{
    months--;
}
print("You are " + months + " months old.");

Comparing Dates

In JScript, 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. If you are using 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 : Date = new Date(); 
var todayAtMidn : Date =
    new Date(now.getFullYear(), now.getMonth(), now.getDate());

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

// Compare the two dates by comparing the millisecond
// representations.
if (todayAtMidn.getTime() == specificDate.getTime())
{
    print("Same");
}
else
{
    print("Different");
}

See Also

Concepts

Data Type Summary