JavaScript Date setDate() Method



The JavaScript Date.setDate() method is used to set the day of the month for this date according to the local time.

This method accepts a parameter "dateValue":

  • If we provide 0 as dateValue, it sets the date to the last day of the previous month.
  • If we provide -1, it sets the date to the day before the last day of the previous month.
  • If we provide a positive value; for example "10", it sets the date to the 10th day of the current month or adds 10 days to the current date.

Syntax

Following is the syntax of JavaScript Date setDate() method −

setDate(dateValue);

Here, the dateValue is an integer representing the day of month.

Return Value

This method returns the number of milliseconds between January 1, 1970 00:00:00 UTC and the updated date. However, the Date object itself is also modified.

Example 1

In the following example, we are using the JavaScript Date setDate() method to set the day of the month to "15" −

<html>
<body>
<script>
   const date = new Date();
   date.setDate(10);

   document.write(date);
</script>
</body>
</html>

Output

As we can see in the output, it sets the day of the month to 15.

Example 2

In this example, we are using the setDate() method to set the date to the last day of the current month −

<html>
<body>
<script>
   const date = new Date();
   date.setDate(0);

   document.write(date);
</script>
</body>
</html>

Output

The above program sets the date to the last day of the current month.

Example 3

Here, we are adding five days to the current date according to local time.−

<html>
<body>
<script>
   const date = new Date();
   date.setDate(date.getDate() + 5);

   document.write(date);
</script>
</body>
</html>

Output

As we can see, five days has been added to the current date.

Example 4

In here, we are subtracting five days from the current date according to local time.

<html>
<body>
<script>
   const date = new Date();
   date.setDate(date.getDate() - 5);

   document.write(date);
</script>
</body>
</html>

Output

As we can see, five days has been subtracted from the current date.

Example 5

The below example sets the date to the same day as the originalDate (current date according to local time).

<html>
<body>
<script>
   const originalDate = new Date(2023, 0, 1); // January 10, 2023
   const newDate = new Date();
   newDate.setDate(originalDate.getDate());

   document.write(newDate);
</script>
</body>
</html>

Output

The provided date has been changed to the actual date.

Advertisements