JavaScripts Temporal API: New era for date and time calculations
Page 3: A big step forward
With the Temporal API, almost everything is getting better in the JavaScript world. At least January is no longer month 0 of the year, which has often led to problems. The interfaces of the various classes are structured much more consistently, meaning that developers rarely have to consult the documentation only to discover that the use case they are looking for cannot be mapped with the Date interface, but requires an additional library.
The new API primarily improves calculations with time and date. The interface allows calculations and comparisons and is able to work with time spans with and without date reference. Consistent support for time zones also makes working in international applications much easier.
The Date class in JavaScript can create new instances with a timestamp. It is therefore necessary to convert a temporal instance into a timestamp. Starting from a PlainDateTime object in the Temporal API, the first step is to create a ZonedDateTime object, which is then converted into an Instant instance. The epochMilliseconds property of this object provides the timestamp. The Date object created with this can be used as usual with the existing libraries, as in the example with the format function of date-fns – admittedly not a nice solution, but certainly not one that will last.
The Temporal API is not yet ready for production, but the polyfill packages and the first fully-fledged reference implementation in the nightly build of Firefox provide an initial insight into the native implementation, which is now gradually finding its way into browsers.
(olb)