Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Temporal

Limited availability

Experimental:This is anexperimental technology
Check theBrowser compatibility table carefully before using this in production.

TheTemporal object enables date and time management in various scenarios, including built-in time zone and calendar representation, wall-clock time conversions, arithmetics, formatting, and more. It is designed as a full replacement for theDate object.

Description

Unlike most global objects,Temporal is not a constructor. You cannot use it with thenew operator or invoke theTemporal object as a function. All properties and methods ofTemporal are static (just like theMath object).

Temporal has an intricate and powerful API. It exposes over 200 utility methods via several classes, so it could appear very complex. We will provide a high-level overview of how these APIs are related to each other.

Background and concepts

JavaScript has had theDate object for handling date and time since its first days. However, theDate API is based on the poorly designedjava.util.Date class from Java, which was replaced in the early 2010s; but, because of JavaScript's goal of backward compatibility,Date sticks around in the language.

The important lesson to preface the whole introduction is thatdate handling is complex. Most of the problems ofDate are fixable by adding more methods, but a fundamental design flaw remains: it exposes so many methods on the same object that developers are often confused about what to use, leading to unexpected pitfalls. A well-designed API not only needs to do more, but also should doless with each level of abstraction, because preventing misuse is as important as enabling use cases.

Date objects wear two hats simultaneously:

  • As atimestamp: the number of milliseconds or nanoseconds elapsed since a fixed point in time (known as theepoch).
  • As a combination ofcomponents: year, month, day, hour, minute, second, millisecond, and nanosecond. The year, month, and day identifiers only make sense with reference to acalendar system. The whole combination maps to a unique instant in history when associated with a time zone.Date objects provide methods for reading and modifying these components.

Time zones underlie a significant number of date-related bugs. When interacting with aDate via the "combination of components" model, the time can only be in two time zones: UTC and local (device), and there's no way to specify an arbitrary time zone. Also lacking is the concept of "no time zone": this is known as acalendar date (for dates) orwall-clock time (for times), which is a time you "read off a calendar or clock". For example, if you are setting a daily wake up alarm, you will want to set it to "8:00AM" regardless of whether it is daylight saving time or not, whether you have traveled to a different time zone, etc.

A second feature lacking fromDate is acalendar system. Most people may be familiar with the Gregorian calendar, where there are two eras, BC and AD; there are 12 months; each month has a different number of days; there's a leap year every 4 years; and so on. However, some of these concepts may not apply when you are working with another calendar system, such as the Hebrew calendar, the Chinese calendar, the Japanese calendar, etc. WithDate, you can only work with the Gregorian calendar model.

There are many other undesirable legacies aboutDate, such as all setters being mutating (which often causes unwanted side effects), thedate time string format being impossible to parse in a consistent way, etc. In the end, the best solution is to build a new API from scratch, which is whatTemporal is.

API overview

Temporal is a namespace, likeIntl. It contains several classes and namespaces, each of which is designed to handle a specific aspect of date and time management. The classes can be grouped as such:

Furthermore, there's also another utility namespace,Temporal.Now, which provides methods for getting the current time in various formats.

Shared class interface

There are many classes in theTemporal namespace, but they share many similar methods. The following table lists all methods of each class (exceptconversion methods):

InstantZonedDateTimePlainDateTimePlainDatePlainTimePlainYearMonthPlainMonthDay
ConstructionInstant()
Instant.from()
Instant.fromEpochMilliseconds()
Instant.fromEpochNanoseconds()
ZonedDateTime()
ZonedDateTime.from()
PlainDateTime()
PlainDateTime.from()
PlainDate()
PlainDate.from()
PlainTime()
PlainTime.from()
PlainYearMonth()
PlainYearMonth.from()
PlainMonthDay()
PlainMonthDay.from()
UpdaterN/Awith()
withCalendar()
withTimeZone()
withPlainTime()
with()
withCalendar()
withPlainTime()
with()
withCalendar()
with()with()with()
Arithmeticadd()
subtract()
since()
until()
add()
subtract()
since()
until()
add()
subtract()
since()
until()
add()
subtract()
since()
until()
add()
subtract()
since()
until()
add()
subtract()
since()
until()
N/A
Roundinground()round()round()N/Around()N/AN/A
Comparisonequals()
Instant.compare()
equals()
ZonedDateTime.compare()
equals()
PlainDateTime.compare()
equals()
PlainDate.compare()
equals()
PlainTime.compare()
equals()
PlainYearMonth.compare()
equals()
SerializationtoJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()
toJSON()
toLocaleString()
toString()
valueOf()

The following table summarizes which properties are available on each class, giving you a sense of what information each class can represent.

InstantZonedDateTimePlainDateTimePlainDatePlainTimePlainYearMonthPlainMonthDay
CalendarN/AcalendarIdcalendarIdcalendarIdN/AcalendarIdcalendarId
Year-relatedN/Aera
eraYear
year
inLeapYear
monthsInYear
daysInYear
era
eraYear
year
inLeapYear
monthsInYear
daysInYear
era
eraYear
year
inLeapYear
monthsInYear
daysInYear
N/Aera
eraYear
year
inLeapYear
monthsInYear
daysInYear
N/A
Month-relatedN/Amonth
monthCode
daysInMonth
month
monthCode
daysInMonth
month
monthCode
daysInMonth
N/Amonth
monthCode
daysInMonth
monthCode
Week-relatedN/AweekOfYear
yearOfWeek
daysInWeek
weekOfYear
yearOfWeek
daysInWeek
weekOfYear
yearOfWeek
daysInWeek
N/AN/AN/A
Day-relatedN/Aday
dayOfWeek
dayOfYear
day
dayOfWeek
dayOfYear
day
dayOfWeek
dayOfYear
N/AN/Aday
Time componentsN/Ahour
minute
second
millisecond
microsecond
nanosecond
hour
minute
second
millisecond
microsecond
nanosecond
N/Ahour
minute
second
millisecond
microsecond
nanosecond
N/AN/A
Time zoneN/AtimeZoneId
offset
offsetNanoseconds
hoursInDay
getTimeZoneTransition()
startOfDay()
N/AN/AN/AN/AN/A
Epoch timeepochMilliseconds
epochNanoseconds
epochMilliseconds
epochNanoseconds
N/AN/AN/AN/AN/A

Conversion between classes

The table below summarizes all conversion methods that exist on each class.

How to convert from...
InstantZonedDateTimePlainDateTimePlainDatePlainTimePlainYearMonthPlainMonthDay
to...Instant/toInstant()Convert toZonedDateTime first
ZonedDateTimetoZonedDateTimeISO()/toZonedDateTime()toZonedDateTime()PlainDate#toZonedDateTime() (pass as argument)Convert toPlainDate first
PlainDateTimeConvert toZonedDateTime firsttoPlainDateTime()/toPlainDateTime()PlainDate#toPlainDateTime() (pass as argument)
PlainDatetoPlainDate()toPlainDate()/No overlap in informationtoPlainDate()toPlainDate()
PlainTimetoPlainTime()toPlainTime()No overlap in information/No overlap in information
PlainYearMonthConvert toPlainDate firsttoPlainYearMonth()No overlap in information/Convert toPlainDate first
PlainMonthDaytoPlainMonthDay()Convert toPlainDate first/

With these tables, you should have a basic idea of how to navigate theTemporal API.

Calendars

A calendar is a way to organize days, typically into periods of weeks, months, years, and eras. Most of the world uses the Gregorian calendar, but there are many other calendars in use, especially in religious and cultural contexts. By default, all calendar-awareTemporal objects use the ISO 8601 calendar system, which is based on the Gregorian calendar and defines additional week-numbering rules.Intl.supportedValuesOf() lists most of the calendars likely to be supported by browsers. Here we provide a brief overview of how calendar systems are formed to help you internalize what factors may vary between calendars.

There are three prominent periodic events on Earth: its rotation around the sun (365.242 days for one revolution), the moon's rotation around the Earth (29.53 days from new moon to new moon), and its rotation around its axis (24 hours from sunrise to sunrise). Every culture has the same measure of a "day", which is 24 hours. Occasional changes such as daylight saving time are not part of the calendar, but are part of thetime zone's information.

  • Some calendars primarily define one year as 365.242 days on average, by defining years to have 365 days, and adding an extra day, theleap day, about every 4 years. Then, the year may be further divided into parts called months. These calendars are calledsolar calendars. The Gregorian calendar and the Solar Hijri calendar are solar calendars.
  • Some calendars primarily define one month as 29.5 days on average, by defining months to alternate between 29 and 30 days. Then, 12 months may be grouped into a year of 354 days. These calendars are calledlunar calendars. The Islamic calendar is a lunar calendar. Because a lunar year is artificial and does not correlate with the season cycle, lunar calendars are generally rarer.
  • Some calendars also primarily define months based on lunar cycles, like lunar calendars. Then, to compensate for the 11-day discrepancy with the solar year, an extra month, theleap month, is added about every 3 years. These calendars are calledlunisolar calendars. The Hebrew calendar and the Chinese calendar are lunisolar calendars.

InTemporal, every date under one calendar system is uniquely identified by three components:year,month, andday. Whileyear is typically a positive integer, it may also be zero or negative, and increases monotonically with time. The year1 (or0, if it exists) is known as the calendar epoch, and is arbitrary for each calendar.month is a positive integer that increments by 1 every time, starting at1 and ending atdate.monthsInYear, then resetting back to1 as the year advances.day is also a positive integer, but it may not start at 1 or increment by 1 every time, because political changes may cause days to be skipped or repeated. But in general,day monotonically increases and resets as the month advances.

In addition toyear, a year can also be uniquely identified by the combination ofera anderaYear, for calendars that use eras. For example, the Gregorian calendar uses the era "CE" (Common Era) and "BCE" (Before Common Era), and the year-1 is the same as{ era: "bce", eraYear: 2 } (note that year0 always exists for all calendars; for the Gregorian calendar, it corresponds to 1 BCE due toastronomical year numbering).era is a lowercase string, anderaYear is an arbitrary integer that may be zero or negative, or even decrease with time (usually for the oldest era).

Note:Always useera anderaYear as a pair; don't use one property without also using the other. In addition, to avoid conflicts, don't combineyear andera/eraYear when designating a year. Pick one year representation and use it consistently.

Be careful of the following incorrect assumptions about years:

  • Don't assume thatera anderaYear are always present; they may beundefined.
  • Don't assume thatera is a user-friendly string; usetoLocaleString() to format your date instead.
  • Don't assume that twoyear values from different calendars are comparable; use thecompare() static method instead.
  • Don't assume that years have 365/366 days and 12 months; usedaysInYear andmonthsInYear instead.
  • Don't assume that leap years (inLeapYear istrue) have one extra day; they may have an extra month.

In addition tomonth, a month in a year can also be uniquely identified by themonthCode.monthCode usually maps to the month's name, butmonth does not. For example, in the case of lunisolar calendars, two months with the samemonthCode, where one belongs to a leap year and the other one does not, will have differentmonth values if they come after the leap month, due to the insertion of an extra month.

Note:To avoid conflicts, don't combinemonth andmonthCode when designating a month. Pick one month representation and use it consistently.month is more useful if you need the order of months in a year (e.g., when looping through the months), whilemonthCode is more useful if you need the name of the month (e.g., when storing birthdays).

Be careful of the following incorrect assumptions about months:

  • Don't assume thatmonthCode andmonth always correspond.
  • Don't assume the number of days in a month; usedaysInMonth instead.
  • Don't assume thatmonthCode is a user-friendly string; usetoLocaleString() to format your date instead.
  • Generally, don't cache the name of months in an array or object. Even thoughmonthCode usually maps to the month's name within one calendar, we recommend always computing the month's name using, for example,date.toLocaleString("en-US", { calendar: date.calendarId, month: "long" }).

In addition today (which is a month-based index), a day in a year can also be uniquely identified by thedayOfYear.dayOfYear is a positive integer that increments by 1 every time, starting at1 and ending atdate.daysInYear.

The concept of a "week" is not connected with any astronomical event, but is a cultural construct. While the most common length is7 days, weeks can also have 4, 5, 6, 8, or more days — or even lack a fixed number of days altogether. To get the specific number of days of the week of a date, use the date'sdaysInWeek.Temporal identifies weeks by the combination ofweekOfYear andyearOfWeek.weekOfYear is a positive integer that increments by 1 every time, starting at1, then resetting back to1 as the year advances.yearOfWeek is generally the same asyear, but may be different at the start or end of each year, because one week may cross two years, andyearOfWeek picks one of the two years based on the calendar's rules.

Note:Always useweekOfYear andyearOfWeek as a pair; don't useweekOfYear andyear.

Be careful of the following incorrect assumptions about weeks:

  • Don't assume thatweekOfYear andyearOfWeek are always present; they may beundefined.
  • Don't assume that weeks are always 7 days long; usedaysInWeek instead.
  • Note that the currentTemporal API does not support year-week dates, so you can't construct dates using these properties or serialize dates to year-week representations. They are only informational properties.

RFC 9557 format

AllTemporal classes can be serialized and deserialized using the format specified inRFC 9557, which is based onISO 8601 / RFC 3339. The format, in its full form, is as follows (spaces are only for readability and should not be present in the actual string):

YYYY-MM-DD T HH:mm:ss.sssssssss Z/±HH:mm [time_zone_id] [u-ca=calendar_id]

Different classes have different requirements for the presence of each component, so you will find a section titled "RFC 9557 format" in each class's documentation, which specifies the format recognized by that class.

This is very similar to thedate time string format used byDate, which is also based on ISO 8601. The main addition is the ability to specify micro- and nanosecond components, and the ability to specify the time zone and calendar system.

Representable dates

AllTemporal objects that represent a specific calendar date impose a similar limit on the range of representable dates, which is ±108 days (inclusive) from the Unix epoch, or the range of instants from-271821-04-20T00:00:00 to+275760-09-13T00:00:00. This is the same range asvalid dates. More specifically:

  • Temporal.Instant andTemporal.ZonedDateTime apply this limit directly on itsepochNanoseconds value.
  • Temporal.PlainDateTime interprets the date-time in the UTC time zone and requires it to be ±(108 + 1) days (exclusive) from the Unix epoch, so its valid range is-271821-04-19T00:00:00 to+275760-09-14T00:00:00, exclusive. This allows anyZonedDateTime to be converted to aPlainDateTime regardless of its offset.
  • Temporal.PlainDate applies the same check asPlainDateTime to the noon (12:00:00) of that date, so its valid range is-271821-04-19 to+275760-09-13. This allows anyPlainDateTime to be converted to aPlainDate regardless of its time, and vice versa.
  • Temporal.PlainYearMonth has the valid range of-271821-04 to+275760-09. This allows anyPlainDate to be converted to aPlainYearMonth regardless of its date (except if a non-ISO month's first day falls in the ISO month-271821-03).

TheTemporal objects will refuse to construct an instance representing a date/time beyond this limit. This includes:

  • Using the constructor orfrom() static method.
  • Using thewith() method to update calendar fields.
  • Usingadd(),subtract(),round(), or any other method to derive new instances.

Static properties

Temporal.DurationExperimental

Represents a difference between two time points, which can be used in date/time arithmetic. It is fundamentally represented as a combination of years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds values.

Temporal.InstantExperimental

Represents a unique point in time, with nanosecond precision. It is fundamentally represented as the number of nanoseconds since the Unix epoch (midnight at the beginning of January 1, 1970, UTC), without any time zone or calendar system.

Temporal.NowExperimental

Provides methods for getting the current time in various formats.

Temporal.PlainDateExperimental

Represents a calendar date (a date without a time or time zone); for example, an event on a calendar which happens during the whole day no matter which time zone it's happening in. It is fundamentally represented as an ISO 8601 calendar date, with year, month, and day fields, and an associated calendar system.

Temporal.PlainDateTimeExperimental

Represents a date (calendar date) and time (wall-clock time) without a time zone. It is fundamentally represented as a combination of adate (with an associated calendar system) and atime.

Temporal.PlainMonthDayExperimental

Represents the month and day of a calendar date, without a year or time zone; for example, an event on a calendar that recurs every year and happens during the whole day. It is fundamentally represented as an ISO 8601 calendar date, with year, month, and day fields, and an associated calendar system. The year is used to disambiguate the month-day in non-ISO calendar systems.

Temporal.PlainTimeExperimental

Represents a time without a date or time zone; for example, a recurring event that happens at the same time every day. It is fundamentally represented as a combination of hour, minute, second, millisecond, microsecond, and nanosecond values.

Temporal.PlainYearMonthExperimental

Represents the year and month of a calendar date, without a day or time zone; for example, an event on a calendar that happens during the whole month. It is fundamentally represented as an ISO 8601 calendar date, with year, month, and day fields, and an associated calendar system. The day is used to disambiguate the year-month in non-ISO calendar systems.

Temporal.ZonedDateTimeExperimental

Represents a date and time with a time zone. It is fundamentally represented as a combination of aninstant, a time zone, and a calendar system.

Temporal[Symbol.toStringTag]

The initial value of the[Symbol.toStringTag] property is the string"Temporal". This property is used inObject.prototype.toString().

Specifications

Specification
Temporal
# sec-temporal-objects

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp