JavaScript date.setMonth(month, day) method
The date.setMonth(month, day)
method in JavaScript is used to set the month of a Date
object according to local time. Optionally, you can also set the day of the month. This method updates the original Date
object.
Syntax:
Parameters:
- month: An integer between
0
and11
representing the month (where 0 = January and 11 = December). - day (optional): An integer representing the day of the month (1 through 31). If not provided, the existing day of the month will be used.
Returns:
- The number of milliseconds since January 1, 1970, 00:00:00 UTC, representing the updated
Date
object.
Example 1: Setting Only the Month
Output:
Explanation:
- The month is updated to January (0), but the day remains the same (22nd).
Example 2: Setting Both Month and Day
Output:
Explanation:
- Both the month is set to March (2) and the day to the 10th, updating the
Date
object.
Example 3: Handling Overflow in Days
If the day exceeds the number of days in the set month, the method will roll over to the next month or year.
Output:
Explanation:
- Since February (in 2024, a leap year) only has 29 days, setting the day to 31 causes the date to roll over to March 2nd.
Example 4: Setting the Month without Changing the Day
If you only provide the month
argument, the existing day of the month is preserved.
Output:
Explanation:
- The month is set to October (9), while the day remains the 15th.
Example 5: Using Negative or Overflowing Values for Month
You can use negative or values greater than 11 for the month, and JavaScript will adjust the year accordingly.
Output:
Explanation:
- Since 12 is an invalid month, it rolls over to January of the next year (2025).
Example 6: Using a Negative Month
Output:
Explanation:
- Setting the month to -1 rolls the date back to November of the previous year (2023).
Summary:
date.setMonth(month, day)
allows you to set the month and optionally the day of aDate
object.- If only the month is specified, the day remains unchanged.
- JavaScript adjusts the date and time if the provided values for the day or month overflow or underflow.