javascriptdatedate-format

JavaScript Intl.DateTimeFormat.format vs Date.toLocaleString


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?

  1. Intl.DateTimeFormat.prototype.format
  2. Date.prototype.toLocaleString()

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"


Solution

  • 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.