• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • Date.prototype.toLocaleString()

    toLocaleString()方法返回该日期对象的字符串,该字符串格式因不同语言而不同。新增的参数localesoptions使程序能够指定使用哪种语言格式化规则,允许定制该方法的表现(behavior)。在旧版本浏览器中,localesoptions参数被忽略,使用的语言环境和返回的字符串格式是各自独立实现的。

    语法

    dateObj.toLocaleString([locales [, options]])
    

    参数

    查看浏览器兼容性小节,看下哪些浏览器支持localesoptions参数,还可以参看例子:检测localesoptions参数支持情况。

    locales Optional

    A string with a BCP 47 language tag, or an array of such strings. To use the browser's default locale, omit this argument or pass undefined. Unicode extension are supported(for example "en-US-u-ca-buddhist"). For the general form and interpretation of the locales argument, see the Intl page. 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"," iso8601"," japanese"," persian"," roc".
    hc
    Hour cycle. Possible values include:" h11"," h12"," h23"," h24".
    options Optional

    An object with some or all of the following properties:

    dateStyle
    The date formatting style to use when calling format(). Possible values include:
    • "full"
    • "long"
    • "medium"
    • "short"
    timeStyle
    The time formatting style to use when calling format(). Possible values include:
    • "full"
    • "long"
    • "medium"
    • "short"
    localeMatcher
    The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page.
    timeZone
    The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai"," Asia/Kolkata"," America/New_York".
    hour12
    Whether to use 12-hour time(as opposed to 24-hour time). Possible values are true and false; the default is locale dependent. This option overrides the hc language tag and/or the hourCycle option in case both are present.
    hourCycle
    The hour cycle to use. Possible values are "h11"," h12"," h23", or "h24". This option overrides the hc language tag, if both are present, and the hour12 option takes precedence in case both options have been specified.
    formatMatcher
    The format matching algorithm to use. Possible values are "basic" and "best fit"; the default is "best fit". See the following paragraphs for information about the use of this property.

    The following properties describe the date-time components to use in formatted output, and their desired representations. Implementations are required to support at least the following subsets:

    • weekday,year,month,day,hour,minute,second
    • weekday,year,month,day
    • year,month,day
    • year,month
    • month,day
    • hour,minute,second
    • hour,minute

    Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic" algorithm and an implementation-dependent "best fit" algorithm.

    weekday
    The representation of the weekday. Possible values are:
    • "long"(e.g.,Thursday)
    • "short"(e.g.,Thu)
    • "narrow"(e.g.,T). Two weekdays may have the same narrow style for some locales(e.g.Tuesday's narrow style is also T).
    era
    The representation of the era. Possible values are:
    • "long"(e.g.,Anno Domini)
    • "short"(e.g.,AD)
    • "narrow"(e.g.,A)
    year
    The representation of the year. Possible values are:
    • "numeric"(e.g.,2012)
    • "2-digit"(e.g.,12)
    month
    The representation of the month. Possible values are:
    • "numeric"(e.g.,2)
    • "2-digit"(e.g.,02)
    • "long"(e.g.,March)
    • "short"(e.g.,Mar)
    • "narrow"(e.g.,M). Two months may have the same narrow style for some locales(e.g.May's narrow style is also M).
    day
    The representation of the day. Possible values are:
    • "numeric"(e.g.,1)
    • "2-digit"(e.g.,01)
    hour
    The representation of the hour. Possible values are "numeric"," 2-digit".
    minute
    The representation of the minute. Possible values are "numeric"," 2-digit".
    second
    The representation of the second. Possible values are "numeric"," 2-digit".
    timeZoneName
    The representation of the time zone name. Possible values are:
    • "long"(e.g.,British Summer Time)
    • "short"(e.g.,GMT+1)

    每个日期时间组件的默认值都是undefined,但是如果weekday,year,month,day,hour,minute,second属性都是undefined,那么year,month,day,hour,minute 和second的值都被认为是"numeric".

    返回值

    根据当地语言规定返回代表着时间的字符串。

    例子

    例子:使用toLocaleString

    没有指定语言环境(locale)时,返回一个使用默认语言环境和格式设置(options)的格式化字符串。

    var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
    
    // toLocaleString 不包含参数的返回值取决于实现,
    // 默认的区域(locale),和默认的时区(time zone)
    date.toLocaleString();
    // → 如果是在en-US区域和America/Los_Angeles时区运行返回值为"12/11/2012, 7:00:00 PM"
    

    例子:检测localesoptions参数支持情况

    localesoptions参数不是所有的浏览器都支持。为了检测一种实现环境(implementation)是否支持它们,可以使用不合法的语言标签,如果实现环境支持该参数,则会抛出一个RangeError异常,反之会忽略参数。

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

    例子:使用locales参数

    下例展示了本地化日期格式的一些变化。为了在应用的用户界面得到某种语言的日期和时间格式,必须确保使用locales参数指定了该语言(可能还需要设置某些回退语言)。

    var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
    
    //假定本地时区是 America/Los_Angeles(美国时区)
    //en-US(美利坚英语)使用 month-day-year 的顺序展示年月日
    alert(date.toLocaleString("en-US"));
    // → "12/19/2012, 7:00:00 PM"
    
    // en-GB(不列颠英语)使用 day-month-year 顺序展示年月日
    alert(date.toLocaleString("en-GB"));
    // → "20/12/2012 03:00:00"
    
    // 韩语使用 year-month-day 顺序展示年月日
    alert(date.toLocaleString("ko-KR"));
    // → "2012. 12. 20. 오후 12:00:00"
    
    // 大多数阿拉伯语国家的阿拉伯语使用阿拉伯数字
    alert(date.toLocaleString("ar-EG"));
    // → "٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص"
    
    //在日本,应用可能想要使用日本日历,
    //2012 是平成24年(平成是是日本天皇明仁的年号,由1989年1月8日起开始计算直至现在)
    alert(date.toLocaleString("ja-JP-u-ca-japanese"));
    // → "24/12/20 12:00:00"
    
    //当请求一个语言可能不支持,如巴厘(ban),若有备用的语言印尼语(id),
    //那么将使用印尼语(id)
    alert(date.toLocaleString(["ban", "id"]));
    // → "20/12/2012 11.00.00"
    

    例子:使用options参数

    可以使用options 参数来自定义toLocaleString方法返回的字符串。

    var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
    
    //请求参数(options)中包含参数星期(weekday),并且该参数的值为长类型(long)
    var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
    alert(date.toLocaleString("de-DE", options));
    // → "Donnerstag, 20. Dezember 2012"
    
    //一个应用使用 世界标准时间(UTC),并且UTC使用短名字(short)展示
    options.timeZone = "UTC";
    options.timeZoneName = "short";//若不写这一行那么仍然显示的是世界标准时间;但是GMT三个字母不会显示
    alert(date.toLocaleString("en-US", options));
    // → "Thursday, December 20, 2012, GMT"
    
    // 使用24小时制
    alert(date.toLocaleString("en-US", {hour12: false}));
    // → "12/19/2012, 19:00:00"
    

    性能

    当格式化大量日期时,最好创建一个Intl.DateTimeFormat对象,然后使用该对象format属性提供的方法。