JavaScript Temporal API Ships in Chrome
Chrome 144 now ships the long-awaited Temporal API, a modern addition to JavaScript for handling dates and times. The API is designed to standardize date/time operations and address a common source of bugs in web development. This native browser support is expected to reduce developer reliance on external libraries for date manipulation.
- The Temporal API is a TC39 proposal currently at Stage 3, indicating a stable specification that is unlikely to change significantly. It has been in development since early 2017 to address long-standing issues with JavaScript's original `Date` object. - JavaScript's original `Date` object, created in 1995, was based on Java's flawed `java.util.Date` and suffers from problems like mutability, unreliable parsing, and poor time zone support. These issues have led developers to rely on libraries like Moment.js, which is now considered a legacy project in maintenance mode. - A key feature of the Temporal API is immutability; all Temporal objects are unchangeable, which prevents common bugs where dates are accidentally modified. Instead of changing an object, operations on Temporal objects return a new instance. - The API introduces distinct objects for different date and time concepts, such as `Temporal.PlainDate` for dates without time or time zone information, `Temporal.ZonedDateTime` for time-zone-aware date-times, and `Temporal.Duration` for representing a length of time. This separation is designed to prevent common errors like unintentionally including time and time zone information. - Browser support for the Temporal API is not yet universal, which may delay its widespread adoption. While Chrome 144 and Firefox 139 have shipped support, Safari has more limited "preview" support. Developers can use polyfills to work with the API in environments where it's not natively supported. - The Temporal API is designed with internationalization as a primary feature, offering built-in support for various calendar systems beyond the Gregorian calendar, such as Hebrew, Islamic, and Chinese. This is a significant improvement over the `Date` object, which does not support non-Gregorian calendars. - The new API offers nanosecond precision, an improvement over the millisecond precision of the original `Date` object. It also provides a global `Temporal` object that acts as a namespace, similar to `Math`, rather than a constructor. - The final standardization of the Temporal API (Stage 4) is partially blocked by the need to standardize the string formats for calendar and time zone annotations with the Internet Engineering Task Force (IETF).