This article mainly introduces the summary of date-related operations in JavaScript, which is the basic knowledge in the JS getting started learning. For more information, see
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, 1975 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, and the date object is automatically converted.
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"); }
How to Use the Date () method to obtain the Date of the current day.
Source code:
《script》var d=new Date();document.write(d);《script》
Test results:
Sat Oct 24 2015 15:14:48 GMT + 0800 (Chinese Standard Time)