Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Date Object

JavaScript Date Object


The Date object is used to work with dates and times.


Online example

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 since January 1, 1970.

setFullYear()
How to use setFullYear() to set a specific date.

toUTCString()
How to use toUTCString() to convert today's date (according to UTC) into a string.

getDay()
How to use getDay() and an array to display the day of the week instead of just a number.

Display a clock
How to display a clock on a web page.


Complete Date object reference

We provide a JavaScript Date object reference, which includes all properties and methods available for Date objects.JavaScript Date object reference。

The reference contains detailed descriptions of each property and method, along with related examples.


Create a date

The Date object is used to work with 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; when not specified, the default 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)


Setting dates

By using methods for Date objects, we can easily manipulate dates.

In the following example, we set a specific date (January 14, 2010) for the Date object:

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 handles the conversion automatically.


Comparing 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日之后"); }