JavaScript setDate function explanation with example:
setDate function is used to set the day to a Date object. It takes only one parameter, i.e. the date.
In this post, we will learn how to use setDate function with examples.
Syntax of setDate:
Below is the complete syntax of setDate :
Date.setDate(day)
Here, day is the day that represents the day of the month. It is an integer value.
We can give any integer value. 1 to 31 are normal date values. 0 represents the last day of the previous month and -1 represents the day before the last day of the last month etc.
Similarly, 32 is the first day of the next month if current month has 31 days. Else, if the current month has 30 days, it will represent the second day of the next month.
Example of setDate:
Let’s take a look at the example below:
var d = new Date("August 10, 1999 10:00:00Z");
console.log(d)
d.setDate(1)
console.log(d)
d.setDate(-5)
console.log(d)
d.setDate(32)
console.log(d)
It will print:
1999-08-10T10:00:00.000Z
1999-08-01T10:00:00.000Z
1999-07-26T10:00:00.000Z
1999-08-01T10:00:00.000Z
Here,
- The first log statement printed the date-time that we created using Date.
- The second statement changed the date to 1st August.
- The third statement changed the date to last month, i.e. 26th July.
- The last statement changed the date to 1st August, because July has 31 days.
You might also like:
- JavaScript program to get the selected value from a dropdown list of items
- How to stop forEach() method in JavaScript
- 3 different JavaScript program to convert a set to array
- JavaScript program to convert Celsius to Fahrenheit
- JavaScript string repeat method
- Example of JavaScript reduce with an array of objects