JavaScript Date setFullYear()

Posted by

Introduction to JavaScript Date setFullYear()

The JavaScript setFullYear() method is used to set the year for a given date according to local time. It takes the year as a parameter and sets the year for the date object.

Syntax

The syntax for the setFullYear() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

dateObj.setFullYear(year[, month[, day]])

[/dm_code_snippet]

The parameters are:

  • year: An integer value representing the year. Must be either a 2-digit or 4-digit year.
  • month: An integer value representing the month (0 – 11).
  • day: An integer value representing the day (1 – 31).

Return Value

The setFullYear() method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

Examples

Let’s look at some examples of using the setFullYear() method.

The following example sets the year to 2020:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let date = new Date();
date.setFullYear(2020);
console.log(date);
// expected output: Thu Jan 01 2020 00:00:00 GMT+0000 (Coordinated Universal Time)

[/dm_code_snippet]

The following example sets the year to 2020, the month to 11 (December), and the day to 15:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let date = new Date();
date.setFullYear(2020, 11, 15);
console.log(date);
// expected output: Sat Dec 15 2020 00:00:00 GMT+0000 (Coordinated Universal Time)

[/dm_code_snippet]

The following example sets the month to 11 (December) and the day to 15, leaving the year unchanged:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let date = new Date();
let currYear = date.getFullYear();
date.setFullYear(currYear, 11, 15);
console.log(date);
// expected output: Sat Dec 15 2019 00:00:00 GMT+0000 (Coordinated Universal Time)

[/dm_code_snippet]

Conclusion

The JavaScript setFullYear() method is used to set the year for a given date according to local time. It takes the year as a parameter and sets the year for the date object.