background

Because the project we developed is used in many countries and regions, different countries and regions have different display habits for dates. For example, we are used to displaying dates in year-month-day format, while the UK is used to displaying dates in day-month-year format. So I’ll introduce the date localization function toLocaleString here.

Introduction to the

The toLocaleString() method returns a string of date objects that varies depending on the locale and configured options. The new arguments locales and options enable the program to specify locale and options. In older browsers, the locales and options arguments are ignored.

let event = new Date(Date.UTC(2012.11.20.3.0.0));

// The UK uses the day-month-year order, 24 hours without AM/PM
event.toLocaleString('en-GB', { timeZone: 'UTC' }); // 20/12/2012, 03:00:00

// South Korea uses the year-month-day order, 12 hours + AM/PM
event.toLocaleString('ko-KR', { timeZone: 'UTC' }); // 2012.12.20. 오전 3:00:00

Copy the code

grammar

dateObj.toLocaleString([locales [, options]])
Copy the code

Check browser compatibility to see which browsers support locales and options, as well as checking for locales and options as an example.

parameter

  • Locales:

    Optionally, the value is a bCP47-compliant language tag string or an array of such strings. If you want to use the browser’s default locale, ignore this parameter or pass undefined.

    Unicode extensions are supported. For example, ‘en-US-U-ca-buddhist’, where ‘en-us’ is the BCP47 language marker, indicating the English language used in the United States. ‘u’ stands for Unicode, indicating a Unicode extension; ‘ca’ stands for Calendar and ‘buddhist’ is the value of CA. The following Unicode extension keys are allowed:

    • nu

      Numbering system. Possible values include: 'arab', 'arabext', 'bali', 'beng', 'deva', 'fullwide', 'gujr', 'guru', 'hanidec', 'khmr', 'knda', 'laoo', 'latn', 'limb', 'mlym', 'mong', 'mymr', 'orya', 'tamldec', 'telu', 'thai', 'tibt'

    • ca

      Calendar. Possible values include: 'buddhist', 'chinese', 'coptic', 'ethiopia', 'ethiopic', 'gregory', 'hebrew', 'indian', 'islamic', 'islamic', 'iso8601', 'japanese', 'persian', 'roc'.

    • hc

      Hour cycle. Possible values include: 'h11', 'h12', 'h23', 'h24'.

    const event = new Date(Date.UTC(2012.11.20.3.0.0));
    event.toLocaleString('en-US', { timeZone: 'UTC' }); // '12/20/2012, 3:00:00 AM'
    event.toLocaleString('en-US-u-ca-buddhist', { timeZone: 'UTC' }); // '12/20/2555, 3:00:00 AM'
    Copy the code

    See Intl Page for more information.

  • Options: Optional object with the following properties:

    • DateStyle: Optional values: ‘full’, ‘long’, ‘medium’, ‘short’.

      const event = new Date(Date.UTC(2012.11.20.3.0.0));
      event.toLocaleString('en-GB', { timeZone: 'UTC' }); / / '20/12/2012, 03:00:00'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.dateStyle: 'full' }); // 'Thursday, 20 December 2012'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.dateStyle: 'long' }); // '20 December 2012'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.dateStyle: 'medium' }); // '20 Dec 2012'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.dateStyle: 'short' }); / / '20/12/2012'
      Copy the code
    • TimeStyle: Optional values: ‘full’, ‘long’, ‘medium’, ‘short’.

      const event = new Date(Date.UTC(2012.11.20.3.0.0));
      event.toLocaleString('en-GB', { timeZone: 'UTC' }); / / '20/12/2012, 03:00:00'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.timeStyle: 'full' }); // '03:00:00 Coordinated Universal Time'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.timeStyle: 'long' }); // '03:00:00 UTC'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.timeStyle: 'medium' }); / / '03:00:00'
      event.toLocaleString('en-GB', { timeZone: 'UTC'.timeStyle: 'short' }); / / '03:00'
      Copy the code
    • LocaleMatcher: locale matching policy. The optional values are ‘lookup’, ‘best fit’; The default value is ‘best fit’. See Intl Page for more information.

    • TimeZone: specifies the timeZone. The optional values are: ‘UTC’; The default value is the default time zone for the current browser. The browser also recognizes the time zone names of the IANA time zone database, for example: ‘Asia/Shanghai’, ‘Asia Kolkata’, ‘America/New_York’.

    • Hour12: Whether to use 12-hour time (corresponding to 24-hour time); Optional values: true, false. The default is locale specific and has a higher priority than hc and hourCycle in the Unicode extension tags in Locales.

    • HourCycle: the hourCycle to use. Optional values: ‘H11 ‘,’ H12 ‘, ‘H23 ‘,’ H24 ‘. It has a higher priority than hc in the Unicode extension tag in Locales and a lower priority than HOUR12.

    • FormatMatcher: formats the matching policy. The optional values are ‘lookup’, ‘best fit’; The default value is ‘best fit’.

    • Weekday: indicates a week. Possible values are as follows:

      • ‘long’ (e.g. Thursday)
      • ‘short’ (e.g. Thu)
      • ‘narrow’ (e.g. T) note that the abbreviations for some areas may be the same, for example: Thursday & Thursday.
    • Era: indicates the era. Possible values are as follows:

      • ‘long’ (e.g. Anno Domini)
      • ‘short’ (e.g. AD)
      • ‘narrow’ (e.g. A)
    • Year: indicates the year. Possible values are as follows:

      • ‘numeric’ (e.g. 2012)
      • ‘2-digit’ (e.g. 12)
    • Month: indicates a month. The value can be:

      • ‘numeric’ (e.g. 2)
      • ‘2-digit’ (e.g. 02)
      • ‘long’ (e.g. March)
      • ‘short’ (e.g. Mar)
      • Note that the shorthand for ‘narrow’ May be the same in some regions, for example: March & May.
    • Day: indicates the day. Possible values are as follows:

      • ‘numeric’ (e.g. 1)
      • ‘2-digit’ (e.g. 01)
    • Hour: represents the hour. The optional value is ‘numeric’ & ‘2-digit’.

    • Minute: specifies the minute, and the optional value is ‘numeric’ & ‘2-digit’

    • Second: represents the second, and the optional values are: ‘numeric’ & ‘2-digit’

    • TimeZoneName: indicates the timeZoneName. Possible values are as follows:

      • ‘long’ (e.g. British Summer Time)
      • ‘short’ (e.g. GMT+1)

Demos

With no arguments

Returns a formatted string using the default locale and formatting options when no locale (locales) is specified.

// The return value of toLocaleString without parameters depends on the current browser's default locales and default time zone. My machine's locale is CN-zh and the time zone is GMT + 8
const event = new Date(Date.UTC(2012.11.20.3.0.0));
event.toLocaleString(); // '2012/12/20 11:00:00 am '

Return '12/19/2012, 7:00:00 PM' if running in en-US and America/Los_Angeles time zone
event.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' }); // '12/19/2012, 7:00:00 PM'
Copy the code

The locales and options parameters are not supported by all browsers. To detect whether the browser supports them, you can use invalid language tags, raising a RangeError if the implementation environment supports the argument, and ignoring the argument otherwise.

function toLocaleStringSupportsLocales() {
    try {
        new Date().toLocaleString('i');
    } catch (e) {
        return e.name === 'RangeError';
    }
    return false;
}
Copy the code

Use the locales parameter

The following example shows the date string output after specifying the locale with the locales parameter.

const date = new Date(Date.UTC(2012.11.20.3.0.0));

// en-us displays the year, month and day in month-day-year order
date.toLocaleString('en-US', { timeZone: 'America/Los_Angeles' }); // '12/19/2012, 7:00:00 PM'

// en-GB displays the day, month and year in day-month-year order
date.toLocaleString('en-GB', { timeZone: 'UTC' }); / / / / '20/12/2012 03:00:00'

// Korean uses year-month-day to display the year, month and day in order
date.toLocaleString('ko-KR', { timeZone: 'Asia/Seoul' }); // '2012.12.20. 오 오 12:00:00'

// In Japan, the program may want to specify the use of a Japanese calendar,
// 2012 is the 24th year of Heisei.
date.toLocaleString('ja-JP-u-ca-japanese', { timeZone: 'Asia/Tokyo' }); / / '24/12/20 12:00:00'

// When requesting a language that may not be supported, such as Bali (BAN), Indonesian (id) will be used if an alternate language is available.
date.toLocaleString(['ban'.'id']); / / '20/12/2012 11.00.00'
Copy the code

Using the options parameter

You can customize the string returned by the toLocaleString method using the options argument.

const date = new Date(Date.UTC(2012.11.20.3.0.0));

// options contains the argument weekday and the value of the argument is long
const options = { weekday: 'long'.year: 'numeric'.month: 'long'.day: 'numeric' };
date.toLocaleString('en-US', options); // 'Thursday, December 20, 2012'

// Specify timeZone as 'UTC'
options.timeZone = 'UTC';
// If timeZoneName is not specified, universal time is still displayed, but UTC three letters are not displayed
options.timeZoneName = 'short';
date.toLocaleString('en-US', options); // 'Thursday, December 20, 2012, UTC'

// Use 24-hour system
date.toLocaleString('en-US', { hour12: false }); / / '12/19/2012, 19:00:00'
Copy the code

Links to other articles

TypeScript trampling tour

[例 句] Build and publish a TypeScript NPM package step by step

NPM install package-lock.json update policy

Browser language preferences

Date.prototype.toLocaleString()