JavaScript date.setFullYear(year, month, day) method
The date.setFullYear(year, month, day)
method in JavaScript is used to set the year (and optionally the month and day) for a specified Date
object according to local time. This method modifies the original Date
object and adjusts the date based on the provided parameters.
Syntax:
Parameters:
- year: An integer representing the year (e.g., 2024).
- month (optional): An integer representing the month (0 for January, 1 for February, etc.). If provided, this will set the month in addition to the year.
- day (optional): An integer representing the day of the month (from 1 to 31). If provided, this will set the day in addition to the year and month.
Returns:
- The number of milliseconds since January 1, 1970, 00:00:00 UTC, representing the updated
Date
object.
Example 1: Setting Only the Year
Output:
Explanation:
- The original date of October 22, 2024, is changed to October 22, 2025.
Example 2: Setting the Year and Month
Output:
Explanation:
- The date is updated to June 22, 2025, as specified.
Example 3: Setting Year, Month, and Day
Output:
Explanation:
- The date is successfully changed to June 15, 2025.
Example 4: Adjusting for Month Length
Output:
Explanation:
- The date is changed to February 28, 2025, as February has only 28 days in a non-leap year.
Example 5: Omitting Optional Parameters
Output:
Explanation:
- The year is changed to 2025, while the month and day remain unchanged.
Summary:
date.setFullYear(year, month, day)
allows you to set the year, and optionally the month and day, for aDate
object.- This method modifies the original
Date
object and handles month and year adjustments, making it useful for date manipulation while considering month lengths and leap years.