ECMAScript's new Temporal
proposal defines (finally!) a modern API for handling dates and times in JS, including timezone-safe arithmetic and non-Gregorian calendars.
I know I can use ISO 8601 or RFC 3339 strings with Temporal
. If I have string data that I want to parse into a JS date/time object, which Temporal type should I use?
To determine the Temporal
class that should be used to parse a string, it's important to pick the type whose data model matches the data in the string.
Temporal.Instant
represents an exact time.
Its data model is the number of integer nanoseconds since January 1, 1970 UTC.
This type is unaware of time zones and does not provide a way to access calendar/clock units like month or hour. It's just a timestamp.Temporal.ZonedDateTime
represents an exact time from the perspective of a specific time zone.
Its data model is a timestamp (like Temporal.Instant
), a time zone (usually an IANA zone), and a calendar.
The time zone is needed because this Temporal
type (and only this type) allows DST-safe creation of derived values.
When you add 1 day to a Temporal.ZonedDateTime
instance, the exact time will usually be 24 hours later but it may be 23 or 25 if the addition crossed a DST transition.Temporal.PlainDate
represents a timezone-less date: a local date without a time and without any reference to the time zone.
Its data model is a year/month/day and a calendar.Temporal.PlainMonthDay
represents a birthday, anniversary, or other recurring event.
Its data model is a month, day, and calendar.Temporal.PlainYearMonth
represents a month in a specific year, e.g. January 2022.
Its data model is a year, month, and calendar.Temporal.PlainTime
represents a timezone-less time of day: a local time without reference to date, time zone, or calendar.
Its data model is an hour/minute/second, with seconds resolution down to 9 decimal digits (nanoseconds).Temporal.PlainDateTime
represents a local date and time without any reference to the time zone.
Its data model is year/month/day/hour/minute/second and a calendar.
This type is rarely used, because the types above cover most use cases.
If you only care about the exact timestamp and don't care about time zones, then use Temporal.Instant
.
If you only care about the local date, then use Temporal.PlainDate
.
If you care about the exact time and the time zone, then use Temporal.ZonedDateTime
.
Other than the few use cases detailed in the Temporal.PlainDateTime
documentation, most of the time it's better to use a different type.Temporal.Duration
represents a period of time.
Its data model is a number of years, months, days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds.Note that localized string formats like '12/25/2022'
and '25/12/2022'
are not parseable by Temporal. Only unambiguous, computer-readable formats can be parsed by Temporal, like '2022-12-25'
.