JavaScript tutorial-JavaScript Date object,
Creation date
The Date object is used to process the Date and time.
You can use the new keyword to define the Date object. The following code defines a Date object named myDate:
There are four ways to initialize the date:
New Date () // current Date and time
New Date (milliseconds) // returns the number of milliseconds since January 1, January 1, 1970
New Date (dateString)
New Date (year, month, day, hours, minutes, seconds, milliseconds)
Most of the above parameters are optional. If not specified, the default parameter is 0.
Examples of instantiating a date:
Var today = new Date ()
Var d1 = new Date ("October 13,197 5 11:13:00 ")
Var d2 = new Date (79,5, 24)
Var d3 = new Date (79,5, 24,11, 33,0)
Set date
By using the date object method, we can easily operate on the date.
In the following example, we set a specific date for the date object (January 1, January 14, 2010 ):
Var myDate = new Date ();
MyDate. setFullYear (2010,0, 14 );
In the following example, we set the date object to the date after 5 days:
Var myDate = new Date ();
MyDate. setDate (myDate. getDate () + 5 );
Note:If the number of days increases, the month or year is changed.
Comparison of Two dates
A date object can also be used to compare two dates.
The following code compares the current date with January 14, 2100:
Var x = new Date ();
X. setFullYear (2100,0, 14 );
Var today = new Date ();
If (x> today)
{
Alert ("Today is before 14th January 2100 ");
}
Else
{
Alert ("Today is after 14th January 2100 ");
}