Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Date Set Method

Date methods allow you to set various date values, such as years, months, days, hours, minutes, seconds, and milliseconds, for a Date Object.

Set Date Methods

Set Date methods are used to set specific parts of a date.

Method

Description

setDate()

Specify the day as a number between 1 and 31.

setFullYear()

Specify the year (optionally month and day)

setHours()

Specify the hour (0-23)

setMilliseconds()

Specify the milliseconds (0-999)

setMinutes()

Specify the minutes (0-59)

setMonth()

Specify the month (0-11)

setSeconds()

Specify the seconds (0-59)

setTime()

Specify the time (milliseconds since January 1, 1970)

The setFullYear() Method

The setFullYear() method updates the year of a date object. In this example, it sets the year to 2020:

Example

const d = new Date();
d.setFullYear(2020);

The setFullYear() method can also optionally set the month and day.

Example

const d = new Date();
d.setFullYear(2020113);

The setMonth() Method

The setMonth() method updates the month of a date object, with values ranging from 0 to 11.

Example

const d = new Date();
d.setMonth(11);

The setDate() Method

The setDate() method updates the day of a date object to a value between 1 and 31.

Example

const d = new Date();
d.setDate(15);

The setDate() method can also be used to add days to a date object.

Example

const d = new Date();
d.setDate(d.getDate() + 50);
If adding days causes the month or year to change, the Date object automatically adjusts accordingly.

The setHours() Method

The setHours() method updates the hours of a date object, with values ranging from 0 to 23.

Example

const d = new Date();
d.setHours(22);

The setMinutes() Method

The setMinutes() method updates the minutes of a date object, with values ranging from 0 to 59.

Example

const d = new Date();
d.setMinutes(30);

The setSeconds() Method

The setSeconds() method updates the seconds of a date object, with values ranging from 0 to 59.

Example

const d = new Date();
d.setSeconds(30);

Compare Dates

Comparing dates is straightforward.

Here’s an example comparing today’s date with January 14, 2100:

Example

let text = “”;
const today = new Date();
const someday = new Date();
someday.setFullYear(2100014);

if (someday > today) {
  text = “Today is before January 14, 2100.”;
else {
  text = “Today is after January 14, 2100.”;
}
In JavaScript, months are indexed from 0 to 11, where January is 0 and December is 11.