Easy Tutorial
❮ Js Class Inheritance Js Summary ❯

JavaScript Date Object


The Date object is used to handle dates and times.


Online Examples

Date()

getFullYear()

getTime()

setFullYear()

toUTCString()

getDay()

Display a clock


Complete Date Object Reference

We provide a JavaScript Date object reference manual, which includes all properties and methods available for the Date object. JavaScript Date Object Reference.

This manual contains detailed descriptions of each property and method, along with relevant examples.


Creating Dates

The Date object is used to handle dates and times.

A Date object can be defined using 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.

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 specific to the Date object, 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);

In the following example, we set the Date object to 5 days in the future:

var myDate = new Date();
myDate.setDate(myDate.getDate() + 5);

Note: If adding days changes the month or year, the Date object will automatically handle this conversion.


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("Today is before January 14, 2100");
} else {
    alert("Today is after January 14, 2100");
}
❮ Js Class Inheritance Js Summary ❯