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
Parameter | Optional/Required | Description |
---|---|---|
yearValue | required | An 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,
- We create a new Date object
date
representing January 1, 2000. - We use the
setYear()
method to set the year ofdate
to 2025. - The updated date is stored in the variable
newDate
. - We log
newDate
to the console usingconsole.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,
- We create a new Date object
date
representing January 1, 2000. - We use the
setYear()
method to set the year ofdate
to 85 (which represents 1985). - The updated date is stored in the variable
newDate
. - We log
newDate
to the console usingconsole.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,
- We create a new Date object
date
representing July 4, 1776. - We use the
setYear()
method to set the year ofdate
to 2000. - The updated date is stored in the variable
newDate
. - We log
newDate
to the console usingconsole.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.