CKTIS / JavaScript
Read and change the UTC year of a Date
`getUTCFullYear()` reads the UTC year. `setUTCFullYear()` changes the same `Date` and returns its new timestamp. Omitting an argument is not the same as passing `undefined`.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
date.getUTCFullYear()
date.setUTCFullYear(year)
date.setUTCFullYear(year, monthIndex)
date.setUTCFullYear(year, monthIndex, dayOfMonth)Date.prototype.getUTCFullYear/setUTCFullYear is the pair of instance methods for reading and changing a Date object's year in UTC. getUTCFullYear() takes no arguments and returns the calendar year as an integer, not a four-digit string, or NaN for an invalid date. By contrast, getFullYear() and setFullYear() use the runtime's local time zone. Near New Year, the same instant can fall in different UTC and local years.
setUTCFullYear(year, monthIndex, dayOfMonth) mutates the existing Date and returns its new timestamp in milliseconds since the Unix epoch. The year is required; the optional month index runs from 0 (January) to 11 (December), and the day of the month starts at 1. To pass a day, pass a month as well. Omitted components and the time of day come from the existing UTC date. Out-of-range calendar components normalize: February 29 becomes March 1 when you change to a non-leap year.
Arguments are converted to numbers. Explicit undefined is not omission: it converts to NaN. If an argument converts to NaN or the resulting timestamp is outside the Date range, the setter stores and returns NaN. If the date was already invalid, the setter starts from 1970-01-01T00:00:00.000Z, so a valid call can repair it.
Unlike Date.UTC(), setUTCFullYear() does not add 1900 to years from 0 through 99. Both prototype methods require a genuine Date as this; calling either with an incompatible receiver throws TypeError.
Examples
const date = new Date('2024-02-29T12:34:56.789Z');
console.log(date.getUTCFullYear());
console.log(date.setUTCFullYear(2023));
console.log(date.toISOString());
console.log(date.setUTCFullYear(2023, undefined));
console.log(date.getUTCFullYear());
date.setUTCFullYear(7);
console.log(date.toISOString());Result
2024 1677674096789 2023-03-01T12:34:56.789Z NaN NaN 0007-01-01T00:00:00.000Z
Changing the year to 2023 rolls February 29 into March 1 without changing the UTC time of day. Explicit `undefined` invalidates the date; setting the year to `7` repairs it to January 1 of year 7 at midnight UTC.
Related lessons
- JavaScript · Lesson 5 · Advanced · Version: 4
Sources
- ECMAScript® 2024 Language Specification — Date.prototype.getUTCFullYear
- ECMAScript® 2024 Language Specification — Date.prototype.setUTCFullYear
- ECMAScript® 2024 Language Specification — Date.UTC
- ECMAScript® 2024 Language Specification — TimeClip
- Date.prototype.getUTCFullYear() - JavaScript | MDN
- Date.prototype.setUTCFullYear() - JavaScript | MDN