JavaScriptで数値、配列、または日付を指定してtoLocaleStringを使用する
toLocaleString
は、システムロケールを使用して日付と時刻を文字列に変換するために使用される組み込みのJavaScriptメソッドです。 🤓🚀
次のJavaScriptタイプで使用できます💪:
- 日付/時刻
- 数字
- オブジェクト
- 配列
日付と時刻を含むtoLocaleString🚀
日付/時刻オブジェクトの場合、toLocaleString
は次のような構文を持ち、文字列を返します🔥👉:
dateObject.toLocaleString(locales, options)
locales
:言語固有の形式を指定するオプションの文字列。 有効な値には、 ar-SA (アラビア語の場合)、 en-US (米国英語の場合)、 hi-IN (ヒンディー語の場合)、があります。 jp-JP (日本語)などoptions
:オプションのオプションオブジェクト。 これに含めることができるいくつかの有効なプロパティは、full
、long
、medium
、およびshort
の値を持つdateStyle
です。 その他の可能なプロパティは、timeStyle
、weekday
、year
、month
、day
、hour
、[ X105X]、 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
:値がlookup
およびbest fit
のlocaleMatcher
などのプロパティを含むことができるオプションのオブジェクト。 その他の有効なプロパティは、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メソッドをサポートしていることを確認することです。