JavaScript Date Object


date objects are used to process dates and times.


Examples

Online Examples

How to use the Date() method to get the date of the day.

getFullYear()
Use getFullYear() to get the year.

getTime()
getTime() returns the number of milliseconds from January 1, 1970 to the present.

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

toUTCString()
How to use toUTCString() to convert the day's date (according to UTC) to a string.

getDay()
How to use getDay() and arrays to display the week of the week, not just the numbers.

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


Complete Date object references

We provide a References for The Date object in JavaScript, which includes all the properties and methods available for date objects. JavaScript Date Object References.

the manual contains a detailed description of each property and method, as well as related examples.


Date created

The Date object is used to process dates and times.

You can define a Date object by 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 above parameters are optional, and the default parameter is 0 when not specified.

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 a date

by using the method for the date object, we can easily manipulate the date.

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);

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 increasing the number of days changes the month or year, the date object automatically completes this conversion.


Comparison of two dates

A date object 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 January 14, 2100");
}
else
{
    alert("Today is after January 14, 2100");
}