JavaScript Date setDate() Method (original) (raw)
Last Updated : 11 Mar, 2024
The setDate()
method in JavaScript is used to set the day of the month for a specified date object, according to local time. It allows you to update the day part of the date without changing other parts like month and year.
**Date setDate() Syntax
dateObj.setDate(date_Value);
**Date setDate() Parameter
This method accepts a single parameter as mentioned above and described below:
- **date_Value: It returns the new i.e updated date of the month which is set by the setDate() method. The date of the month is an integer value ranging from 1 to 31.
**Date setDate() Return value:
This method returns the number of milliseconds between the date object and midnight of January 1, 1970
**Note: DateObj is a valid Date object created using **Date() constructor in which we want to set the date of a month.
JavaScript Date setDate() Method Examples
Example 1: Updating Day of the Month with JavaScript’s setDate()
In this example, we create a new Date object representing February 15, 2022. Then, we use setDate(20)
to update the day of the month to the 20th. The resulting date object now represents February 20, 2022.
Javascript
let date =
new
Date(
'2022-02-15'
);
console.log(date);
date.setDate(20);
console.log(date);
Output
2022-02-15T00:00:00.000Z 2022-02-20T00:00:00.000Z
Example 2: Adding 7 Days to Current Date in JavaScript
A Date object date
is initialized with the current date. setDate()
method is used with getDate()
to add 7 days. The updated date, representing the date 7 days later, is logged.
Javascript
let date =
new
Date();
console.log(date);
date.setDate(date.getDate() + 7);
console.log(date);
Output
2024-03-08T11:22:29.251Z 2024-03-15T11:22:29.251Z
We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.
**Supported Browsers:
The browsers supported by the **JavaScript Date setDate() method are listed below:
- Google Chrome
- Internet Explorer
- Mozilla Firefox
- Opera
- Safari
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.