The Date object is a data type built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.
The setDate() function of the date object accepts an integer representing the day of the month and modifies/replaces the current date with it.
Syntax
Its Syntax is as follows
dateObj.setDate(5);
Example
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var dateObj = new Date('september 26, 89 12:4:25:96'); document.write("Current date: "+dateObj.toUTCString()); document.write("<br>"); dateObj.setDate(1); document.write("Date after modification: "+dateObj.toUTCString()); </script> </body> </html>
Output
Current date: Tue, 26 Sep 1989 06:34:25 GMT Date after modification: Fri, 01 Sep 1989 06:34:25 GMTMT
Example
Though you do not mention the date of the month while creating the date object, You can still set it using the setDate() function.
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var dateObj = new Date('August, 1989 00:4:00'); document.write("<br>"); dateObj.setDate(5) document.write(dateObj.toDateString()); </script> </body> </html>
Output
Sat Aug 05 1989
Example
In the same way, though you do not pass any value to the constructor while creating the date object still you can set the Date using this function and the month and year value remain same as the current date.
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var dateObj = new Date(); dateObj.setDate(2); document.write(dateObj.toDateString()); </script> </body> </html>
Output
Tue Oct 02 2018
Example
If you set the date using this function to zero then the date will be set to the last day of the previous month.
<html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var dateObj = new Date('23, August, 1989 00:4:00'); document.write("<br>"); dateObj.setDate(0); document.write(dateObj.toDateString()); </script> </body> </html>
Output
Mon Jul 31 1989