JavaScript DateObjects
The Date object is used to handle dates and times.
Online Examples
Date()
How to use the Date() method to get today's date.
getFullYear()
Use getFullYear() to get the year.
getTime()
getTime() returns the number of milliseconds from January 1, 1970 to now.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
How to use getDay() and an array to display the weekday, not just a number.
Display a clock
How to display a clock on a web page.
Complete Date Object Reference Manual
We provide a JavaScript Date object reference manual, which includes all the properties and methods available for date objects.JavaScript Date Object Reference Manual。
This manual contains detailed descriptions of each property and method along with related examples.
Create Date
The Date object is used to handle dates and times.
A Date object can be defined with the new keyword. The following code defines a Date object named myDate:
There are four ways to initialize a date:
new Date(); new Date(value); new Date(dateString); new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Most of the parameters above 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
By using methods for the date object, we can easily operate on dates.
In the following example, we set a specific date for the date object (January 14, 2010):
var myDate=new Date(); myDate.setFullYear(2010,0,14);// 第二个参数为月份, 0 到 11 之间的整数值,表示从一月到十二月
In the following example, we set the date object to a date 5 days later:
var myDate=new Date(); myDate.setDate(myDate.getDate()+5);
Note:If adding days changes the month or year, the date object automatically performs this conversion.
Compare Two Dates
Date objects 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("今天是2100年1月14日之前");
}
else
{
alert("今天是2100年1月14日之后");
}
Other Extensions