问题描述
我想使用格式化日期,并在示例中说明
I want to use Intl.DateTimeFormat
to format a Date, and in the examples it says
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
很好,所以我希望我的后备是 ISO 8601 ,如果语言不存在
Great, so I want my fallback to be ISO 8601 in the case a language doesn't exist
// i.e. the same as/similar to
new Date().toISOString(); // "2014-07-31T02:42:06.702Z"
但是
// Intl.DateTimeFormat([locales [, options]])
var o = {};
o.year = o.month = o.day = o.hour = o.minute = o.second = 'numeric';
new Intl.DateTimeFormat(['foo', 'iso8601'], o);
// RangeError: Invalid language tag: iso8601
这似乎是因为 iso8601
不属于
我'我也尝试使用我所知道的作品,例如带有 u-ca-iso8601
后缀的 en-GB
但如果没有后缀,这不会产生任何不同的结果
I've also tried using one I know works, e.g. en-GB
with a u-ca-iso8601
suffix but this doesn't produce any different result to without the suffix
var f = new Intl.DateTimeFormat(['foo', 'en-GB-u-ca-iso8601'], o);
f.format(new Date());
// 31/7/2014 03:35:26
为什么不是这个工作?是否有一个 locale
哪个会给我输出我想要的输出?
Why isn't this working? Is there even a locale
which will give me the output I'm looking for?
我宁愿不必使用例如
if (Intl.DateTimeFormat.supportedLocalesOf(['foo']).length === 0)
推荐答案
由于似乎没有办法在 Intl
中自定义语言环境的定义,因此您需要找到使用ISO 8601格式的语言环境。在,我发现有些类似于ISO 8601.但是,不保证在浏览器或其他JavaScript实现中对特定语言环境的支持。
Since there does not seem to be a way to customize the definitions of locales in Intl
, you would need to find a locale that uses an ISO 8601 format. Checking the CLDR definitions for the yMd format in By-Type Chart: Date & Time:Gregorian, I found some that resemble ISO 8601. However, support to specific locales in browsers or other JavaScript implementations is not guaranteed.
在实践中,在CLDR中的这些区域设置中, fo
(法罗语)似乎最接近ISO 8601并受浏览器支持。使用 Intl.DateTimeFormat(['foo','iso8601'],o)
进行测试会得到以下结果:
In practice, among such locales in CLDR, fo
(Faroese) seems to come closest to being ISO 8601 and supported by browsers. Testing with Intl.DateTimeFormat(['foo', 'iso8601'], o)
gives the following results:
2014-7-31 10:26:50 in Chrome
2014-07-31 10:26:50 in Firefox and IE
因此,Chrome并未完全应用正确的(根据CLDR)格式,并且所有这些浏览器都使用空格而不是 T
作为分隔符。然而,这个空间使得演示文稿更具可读性,现在它已被接受为当前的ISO 8601,即ISO 8601:2004,它说,
Thus, Chrome does not quite apply the correct (as per CLDR) format, and all of these browsers use a space and not T
as a separator. However, the space makes the presentation more readable, and it is now accepted alternative according to current ISO 8601, namely ISO 8601:2004, which says,
然而,使用包装器似乎更安全,如问题所示;与使用某些选定区域设置的风险和kludgy性质相比,它并不太复杂。 (即使所有实现都支持 fo
,也不能保证法罗群岛当局不会决定必须更改区域设置定义。)
However, it seems safer to use a wrapper, as in the question; it’s not too complicated, compared with the risks and kludgy nature of using some selected locale. (Even if fo
is supported by all implementations, there is no guarantee that Faroese authorities won’t decide that the locale definition must be changed.)
这篇关于使用Intl.DateTimeFormat获取ISO 8601的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!