Creation date
Date object is used to handle date and time.
Date objects can be defined using the new keyword. The following code defines a Date object named myDate:
There are four ways to initialize the date:
new Date() // 当前日期和时间 new Date(milliseconds) //返回从 1970 年 1 月 1 日至今的毫秒数 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.
Some 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
We can easily operate on dates by using methods on date objects.
In the example below, we set a specific date (January 14, 2010) for the date object:
var myDate=new Date(); myDate.setFullYear(2010,0,14);
In the example below, we set the date object to a date 5 days from now:
var myDate=new Date(); myDate.setDate(myDate.getDate()+5);
Note: If adding days would change the month or year, the date object will automatically complete this conversion.
Comparison of two dates
Date objects can also be used to compare two dates.
The following code compares the current date to 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 get today’s date.
Source code:
<!DOCTYPE html> <html> <body> ​ <script> ​ var d=new Date(); document.write(d); ​ </script> ​ </body> </html>
Test results:
Sat Oct 24 2015 15:14:48 GMT+0800 (中国标准时间)