JavaScript Date setDate()
Syntax & Examples


setDate() method

The setDate() method of the Date object in JavaScript sets the day of the month for a specified date according to local time.


Syntax of setDate()

The syntax of Date.setDate() method is:

setDate(dateValue)

This setDate() method of Date sets the day of the month for a specified date according to local time.

Parameters

ParameterOptional/RequiredDescription

Return Type

Date.setDate() returns value of type Number.



✐ Examples

1 Using setDate() to set the day of the month

In JavaScript, we can use the setDate() method to set the day of the month for a Date object.

For example,

  1. We create a new Date object date representing January 15, 2021.
  2. We use the setDate() method to set the day of the month to the 25th.
  3. The updated date is stored in the variable updatedDate.
  4. We log updatedDate to the console using console.log() method.

JavaScript Program

const date = new Date('2021-01-15');
date.setDate(25);
console.log(date);

Output

2021-01-25T00:00:00.000Z

2 Using setDate() to set the day of the month beyond the current month

In JavaScript, we can use the setDate() method to set the day of the month beyond the current month, which will adjust the date accordingly.

For example,

  1. We create a new Date object date representing January 15, 2021.
  2. We use the setDate() method to set the day of the month to the 32nd, which will move the date to February 1, 2021.
  3. The updated date is stored in the variable updatedDate.
  4. We log updatedDate to the console using console.log() method.

JavaScript Program

const date = new Date('2021-01-15');
date.setDate(32);
console.log(date);

Output

2021-02-01T00:00:00.000Z

3 Using setDate() with negative values

In JavaScript, we can use the setDate() method with negative values to set the date relative to the end of the previous month.

For example,

  1. We create a new Date object date representing February 15, 2021.
  2. We use the setDate() method to set the day of the month to -1, which will move the date to January 30, 2021.
  3. The updated date is stored in the variable updatedDate.
  4. We log updatedDate to the console using console.log() method.

JavaScript Program

const date = new Date('2021-02-15');
date.setDate(-1);
console.log(date);

Output

2021-01-30T00:00:00.000Z

Summary

In this JavaScript tutorial, we learned about setDate() method of Date: the syntax and few working examples with output and detailed explanation for each example.