The setDate
function in JavaScript is a method of the Date
class with the following syntax:
setDate(dayValue)
dayValue
is an integer that denotes the day of the month. Normally, the range is 1
to the last day of the month (e.g., 31
for January). However, the value can be 0
, which denotes the last day of the previous month. Negative values denote days before the last day of the previous month. Positive values greater than the specified month’s last day increase the month and the day accordingly.setDate()
returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC until the updated time.The setDate
function is called on a Date
object, which updates the day of the month in the Date
object.
The following code demonstrates the usage of the setDate
function:
const date = new Date(2021, 6, 5);console.log(date);date.setDate(1)console.log(date);date.setDate(0)console.log(date);date.setDate(32)console.log(date);date.setDate(-1)console.log(date);
In the example above, the initial value of date
is 7th July 2021
. After date.setDate(1)
is called, the date
becomes 1st July 2021
. When 0
is passed as an argument to the setDate
function, this results in the date being set to the last day of the previous month; hence, after line 7 executes, the date
becomes 30th June 2021
.
Furthermore, when a day greater than the month’s latest date is passed, the resulting date is for the month after this month. So, when line 10 executes, the date
becomes 2nd July 2021
.
If a negative value is passed to the setDate
function, then it counts backward from the last date of the previous month. Passing -1
in line 13 then results in the date 29th June 2021
.
Free Resources