toLocaleString
是一个内置的JavaScript方法,用于将日期和时间转换为使用系统局域的字符串。
它可以使用以下 JavaScript 类型:
- 日期/时间
- 数字
- 对象
- 数组
toLocaleString 与日期和时间
对于日期/时间对象,‘toLocaleString’具有这样的语法,并返回一个字符串 🔥👉:
1dateObject.toLocaleString(locales, options)
locales
: 指定特定语言格式的可选字符串. 某些有效值为 ar-SA(用于阿拉伯语), en-US(用于美国英语), hi-IN(用于汉语), jp-JP(用于日语),等等.选项
: 选项的可选对象. 其中可以包含的某些有效属性是dateStyle
值为full
,long
,medium
和short
。 其他可能属性是timeStyle
,weekday
,year
,month
,day
,hour
,minute
,second
等。 _
例子
1const date = new Date();
2
3console.log(date.toLocaleString(`en-US`));
4// 11/10/2019, 4:32:44 PM
5
6console.log(date.toLocaleString(`hi-IN`));
7// 10/11/2019, 4:32:44 pm
8
9console.log(date.toLocaleString(`fr-CH`));
10// 10.11.2019 à 16:32:44
11
12const options = {
13 weekday: 'long',
14 era: 'long'
15}
16
17console.log(date.toLocaleString(`en-US`, options));
18// Sunday Anno Domini
19
20console.log(date.toLocaleString(`hi-IN`, options));
21// ईसवी सन रविवार
22
23console.log(date.toLocaleString(`fr-CH`, options));
24// après Jésus-Christ dimanche
与数字相连
对于数字,用toLocaleString
将数字转换为一个特定于本地的数字表示。它具有如下类似的语法,并返回一个字符串 🔥👉:
1number.toLocaleString(locales, options)
locales
:指定本地的可选字符串options
: 可包含值lookup
和best fit
的属性,如localeMatcher
等可选对象。
例子
1const number = 12345.678;
2
3console.log(number.toLocaleString('en-US'));
4// 12,345.678
5
6console.log(number.toLocaleString('fr-FR'));
7// 12 345,678
8
9console.log(number.toLocaleString('en-US', {
10 style: 'currency',
11 currency: 'USD' // With currency, the currency code is also required
12})); // $12,345.68
13
14console.log(number.toLocaleString('hi-IN', {
15 style: 'currency',
16 currency: 'INR'
17})); // ₹12,345.68
18
19console.log(number.toLocaleString('en-US', {
20 style: 'currency',
21 currency: 'USD',
22 maximumSignificantDigits: 2
23})); // $12,000
与 Arrays 同步
在数组中,使用 toLocaleString
将它们转换为特定区域的表示. 语法如下,然后再次返回一个字符串 🔥👉:
1array.toLocaleString(locales, options)
locales
:指定 locale 的可选字符串options
: 可供数字和日期使用的相同选项的可选对象
例子
1const arr = [12345678, new Date(), "alligators"];
2console.log(arr.toLocaleString(`fr-FR`,{
3 style: 'currency',
4 currency: 'EUR',
5 era: 'long'
6}));
7
8// 12 345 678,00 €,10 11 2019 après Jésus-Christ à 18:30:03,alligators
9
10const arr2 = [12345678, new Date(), "alligators"];
11console.log(arr.toLocaleString(`en-US`,{
12 style: 'currency',
13 currency: 'USD',
14 era: 'long'
15}));
16
17// $12,345,678.00,11 10, 2019 Anno Domini, 6:31:56 PM,alligators
注意:如果 local 被省略或未定义,则使用默认系统 local。
现在剩下的就是确保你的目标浏览器 支持 toLocaleString 方法。