JavaScript Date setYear()
Syntax & Examples


Date.setYear() method

The setYear() method of the Date object in JavaScript sets the year (usually 2–3 digits) for a specified date according to local time. It is recommended to use setFullYear() instead.


Syntax of Date.setYear()

The syntax of Date.setYear() method is:

setYear(yearValue)

This setYear() method of Date sets the year (usually 2–3 digits) for a specified date according to local time. Use setFullYear() instead.

Parameters

ParameterOptional/RequiredDescription
yearValuerequiredAn integer representing the year to be set. If a two-digit number is provided, it is treated as the year 1900 plus that number.

Return Type

Date.setYear() returns value of type Number.



✐ Examples

1 Using setYear() to set the year to 2025

In JavaScript, we can use the setYear() method to set the year of a Date object to 2025.

For example,

  1. We create a new Date object date representing January 1, 2000.
  2. We use the setYear() method to set the year of date to 2025.
  3. The updated date is stored in the variable newDate.
  4. We log newDate to the console using console.log() method.

JavaScript Program

const date = new Date('2000-01-01');
date.setYear(2025);
console.log(date);

Output

Wed Jan 01 2025 00:00:00 GMT+0000 (Coordinated Universal Time)

2 Using setYear() with a two-digit year

In JavaScript, we can use the setYear() method to set the year of a Date object using a two-digit number, which will be treated as 1900 plus the given number.

For example,

  1. We create a new Date object date representing January 1, 2000.
  2. We use the setYear() method to set the year of date to 85 (which represents 1985).
  3. The updated date is stored in the variable newDate.
  4. We log newDate to the console using console.log() method.

JavaScript Program

const date = new Date('2000-01-01');
date.setYear(85);
console.log(date);

Output

Tue Jan 01 1985 00:00:00 GMT+0000 (Coordinated Universal Time)

3 Using setYear() to set the year to a date object

In JavaScript, we can use the setYear() method to change the year of an existing Date object to a specific year.

For example,

  1. We create a new Date object date representing July 4, 1776.
  2. We use the setYear() method to set the year of date to 2000.
  3. The updated date is stored in the variable newDate.
  4. We log newDate to the console using console.log() method.

JavaScript Program

const date = new Date('1776-07-04');
date.setYear(2000);
console.log(date);

Output

Tue Jul 04 2000 00:00:00 GMT+0000 (Coordinated Universal Time)

Summary

In this JavaScript tutorial, we learned about setYear() method of Date: the syntax and few working examples with output and detailed explanation for each example.