JavaScript setDate(day) method
The date.setDate(day)
method in JavaScript sets the day of the month for a specified Date
object according to local time. It modifies the original Date
object and can handle month changes if the specified day exceeds the number of days in the month.
Syntax:
Parameters:
- day: An integer representing the day of the month (from 1 to 31).
Returns:
- The number of milliseconds since January 1, 1970, 00:00:00 UTC, representing the updated
Date
object.
Example 1: Setting the Day of the Month
Output:
Explanation:
- The original date of October 22, 2024, is changed to October 15, 2024, as specified by
setDate(15)
.
Example 2: Setting the Day Beyond Month Length
Output:
Explanation:
- The date is successfully changed to January 31, 2024.
Example 3: Setting the Day to a Value Exceeding Month Length
Output:
Explanation:
- When trying to set the date to 32, JavaScript automatically adjusts the date to February 1, 2024, since January has only 31 days.
Example 4: Using Negative Values
Output:
Explanation:
- Setting the date to
-1
adjusts the date to the last day of February 2024 (a leap year), which is February 29.
Summary:
date.setDate(day)
sets the day of the month for aDate
object and can automatically handle month boundaries and leap years.- It modifies the original
Date
object and returns the timestamp in milliseconds since January 1, 1970, UTC. This makes it flexible for manipulating dates and managing different month lengths.