JavaScript Intl.DateTimeFormat.format vs Date.toLocaleString JavaScript Intl.DateTimeFormat.format vs Date.toLocaleString javascript javascript

JavaScript Intl.DateTimeFormat.format vs Date.toLocaleString


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.


Addition to points that others issued, I saw a difference with default formats (options):

const event = new Date(1521065710000)//const o = optionsconsole.log(event.toLocaleString('en-US' /*, o*/))  // "3/15/2018, 1:45:10 AM"console.log(new Intl.DateTimeFormat('en-US' /*, o*/).format(event))  // "3/15/2018"