I would like to print a string representing a Date, using a specific timezone, locale, and display options.
Which one of these should I use?
It seems like they return identical results.
const event = new Date(1521065710000); const options = { day: 'numeric', month: 'long', weekday: 'short', hour: 'numeric', minute: 'numeric', timeZoneName: 'short', timeZone: 'America/Los_Angeles', }; console.log(event.toLocaleString('en-US', options)); // "Wed, March 14, 3:15 PM PDT" console.log(new Intl.DateTimeFormat('en-US', options).format(event)); // "Wed, March 14, 3:15 PM PDT"
The Intl. DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.
The toLocaleString() method returns a string with a language-sensitive representation of this date. In implementations with Intl. DateTimeFormat API support, this method simply calls Intl. DateTimeFormat .
To get the current date and time in JavaScript, you can use the toLocaleString() method, which returns a string representing the given date according to language-specific conventions. To display only the time, you can use the toLocaleTimeString() method.
This is very close to being off–topic as opinion based, but here goes anyway.
Which one of these should I use?
Date.prototype.toLocaleString was originally solely implementation dependent and varied quite a bit across browsers. When support for the Intl object was added (ECMAScript 2015, ed 6) then toLocaleString was allowed to support the same options. While support isn't mandated by ECMA-262, probably all current implementations support it.
Note that this did not remove the allowed implementation variability, it just provided some formatting options based on language, region and dialect (and also timezone options based on the IANA time zone database identifiers and values).
The Intl object (and hence toLocaleString) is based on ECMA-402, which doesn't strictly specify formatting, so there is still some room for implementations to differ. The biggest differences are in regard to timezone names (for which there is no standard) and placement of commas, spaces, etc.
However, for most practical purposes, whether you use the Intl object or toLocaleString is up to you, I don't think there's any technical reason to prefer one over the other. While the results for both should be identical for a particular implementation, don't expect the resulting string to be exactly identical across implementations or to conform to a particular format for a given BCP 47 language tag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With