Home »
JavaScript
Date setDate() method with example in JavaScript
JavaScript Date setDate() method: Here, we are going to learn about the setDate() method in JavaScript with example.
Submitted by IncludeHelp, on March 12, 2019
JavaScript Date setDate() method
setDate() method is a Date class method, it is used to set the current date (day of the month) to the Date object with a valid date value (between 1 to 31, based on the current month).
Note: Date larger than the last date of the month will be truncated from the starting date, for example, in the March there are 31 days and you set the date value to 33, then it will set to the date as the second day of the month (2 March).
Syntax
var dt = new Date();
dt.setDate(day);
Sample Input/Output
Input/Date class object declaration:
var dt = new Date();
Function call to set the date:
dt.setDate(17);
Function call to get the date:
dt.getDate();
Output:
17
JavaScript code to demonstrate an example of Date.setDate() method
<html>
<head><title>JavaScipt Example</title></head>
<body>
<script>
var dt = new Date();
//getting current date (day of the month)
var date = dt.getDate();
//printing
document.write("date: " + date + "<br>");
//setting date to 17
dt.setDate(17);
//getting & printing date again
date = dt.getDate();
document.write("date: " + date + "<br>");
//setting invalid date
//setting date to 33
//This is March month, when I am writing this code
//maximum month in March is 31, thus, 33 will set
//date as 2
dt.setDate(33);
//getting & printing date again
date = dt.getDate();
document.write("date: " + date + "<br>");
</script>
</body>
</html>
Output
date: 12
date: 17
date: 2
Reference: JavaScript setDate() Method
JavaScript Date Object Methods »