Page 159 - DCAP408_WEB_PROGRAMMING
P. 159
Unit 5: Scripting Language
5.7.2 Date Object Notes
The Date object is used to work with dates and times.
Date objects are created with the Date () constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the
object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January 1970 00:00:00 Universal Time (UTC)
with a day containing 86,400,000 milliseconds.
Example: Some examples of instantiating a date:
today = new Date()
d1 = new Date(“October 13, 1975 11:13:00”)
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Notes If adding five days to a date shifts the month or year, the Date object itself handles
the changes automatically!
Compare Two Dates
The Date object is also used to compare two dates.
The following example compares today’s date with the 14th January 2010:
LOVELY PROFESSIONAL UNIVERSITY 153