toLocaleString は、システムロケールを使用して日付と時刻を文字列に変換するために使用される組み込みのJavaScriptメソッドです。 🤓🚀

次のJavaScriptタイプで使用できます💪:

  • 日付/時刻
  • 数字
  • オブジェクト
  • 配列

日付と時刻を含むtoLocaleString🚀

日付/時刻オブジェクトを使用して、 toLocaleString このような構文があり、文字列を返します🔥👉:

dateObject.toLocaleString(locales, options)
  • locales:言語固有の形式を指定するオプションの文字列。 有効な値には、 ar-SA (アラビア語の場合)、 en-US (米国英語の場合)、 hi-IN (ヒンディー語の場合)、があります。 jp-JP (日本語)など
  • options:オプションのオプションオブジェクト。 これに含めることができるいくつかの有効なプロパティは次のとおりです。 dateStyle の値で full, long, mediumshort. その他の可能なプロパティは次のとおりです。 timeStyle, weekday, year, month, day, hour, minute, second、など。

例😍

const date = new Date();

console.log(date.toLocaleString(`en-US`)); 
// 11/10/2019, 4:32:44 PM

console.log(date.toLocaleString(`hi-IN`));
// 10/11/2019, 4:32:44 pm

console.log(date.toLocaleString(`fr-CH`));
// 10.11.2019 à 16:32:44

const options = {
  weekday: 'long',
  era: 'long'
}

console.log(date.toLocaleString(`en-US`, options)); 
// Sunday Anno Domini

console.log(date.toLocaleString(`hi-IN`, options));
// ईसवी सन रविवार

console.log(date.toLocaleString(`fr-CH`, options));
// après Jésus-Christ dimanche

toLocaleStringwithNumbers🚀

数字で、 toLocaleString 数値をロケール固有の数値表現に変換するために使用されます。 次のような構文があり、文字列🔥👉を返します。

number.toLocaleString(locales, options)
  • locales:ロケールを指定するオプションの文字列。
  • options:次のようなプロパティを含むことができるオプションのオブジェクト localeMatcher 値付き lookupbest fit. その他の有効なプロパティは次のとおりです。 style, currency, useGrouping, minimumSignificantDigits、など。

例😍

const number = 12345.678;

console.log(number.toLocaleString('en-US')); 
// 12,345.678

console.log(number.toLocaleString('fr-FR')); 
// 12 345,678

console.log(number.toLocaleString('en-US', {
  style: 'currency',
  currency: 'USD'   // With currency, the currency code is also required
}));  // $12,345.68

console.log(number.toLocaleString('hi-IN', {
  style: 'currency',
  currency: 'INR'
}));  // ₹12,345.68

console.log(number.toLocaleString('en-US', {
  style: 'currency',
  currency: 'USD',
  maximumSignificantDigits: 2
}));  // $12,000

配列を使用したtoLocaleString🚀

アレイの場合、 toLocaleString それらをロケール固有の表現に変換するために使用されます。 構文は次のとおりで、もう一度文字列が返されます🔥👉:

array.toLocaleString(locales, options)
  • locales:ロケールを指定するオプションの文字列。
  • options:数値と日付に使用できる同じオプションのオプションのオブジェクト。

例😍

const arr = [12345678, new Date(), "alligators"];
console.log(arr.toLocaleString(`fr-FR`,{
  style: 'currency',
  currency: 'EUR',
  era: 'long'
}));

//  12 345 678,00 €,10 11 2019 après Jésus-Christ à 18:30:03,alligators

const arr2 = [12345678, new Date(), "alligators"];
console.log(arr.toLocaleString(`en-US`,{
  style: 'currency',
  currency: 'USD',
  era: 'long'
}));

//  $12,345,678.00,11 10, 2019 Anno Domini, 6:31:56 PM,alligators

注:ロケールが省略されているか、未定義のままになっている場合は、デフォルトのシステムロケールが使用されます。 🧪


🥓残りは、ターゲットブラウザがtoLocaleStringメソッドをサポートしていることを確認することです。