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:

date.setFullYear(year[, month[, day]]);

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

const date = new Date('2024-10-22'); // October 22, 2024 date.setFullYear(2025); // Change the year to 2025 console.log(date);

Output:

2025-10-22T00:00:00.000Z

Explanation:

  • The original date of October 22, 2024, is changed to October 22, 2025.

Example 2: Setting the Year and Month

const date = new Date('2024-10-22'); // October 22, 2024 date.setFullYear(2025, 5); // Change the year to 2025 and the month to June (5) console.log(date);

Output:

2025-06-22T00:00:00.000Z

Explanation:

  • The date is updated to June 22, 2025, as specified.

Example 3: Setting Year, Month, and Day

const date = new Date('2024-10-22'); // October 22, 2024 date.setFullYear(2025, 5, 15); // Change to June 15, 2025 console.log(date);

Output:

2025-06-15T00:00:00.000Z

Explanation:

  • The date is successfully changed to June 15, 2025.

Example 4: Adjusting for Month Length

const date = new Date('2024-01-31'); // January 31, 2024 date.setFullYear(2025, 1); // Change to February 2025 console.log(date);

Output:

2025-02-28T00:00:00.000Z

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

const date = new Date('2024-10-22'); // October 22, 2024 date.setFullYear(2025); // Change only the year console.log(date);

Output:

2025-10-22T00:00:00.000Z

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 a Date 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.