简体   繁体   English

明确而有用的时间格式

[英]Unambiguous and useful time formatting

I can produce a locally-formatted time for visitors: 我可以为访问者生成本地格式的时间:

var expires = XXXX
$('#expires').text(new Date(expires).toLocaleTimeString())

For example, this produces 12:05:46 PM. 例如,这产生12:05:46 PM。 However this is ambiguous for the visitor. 但是,这对于访客来说是模棱两可的。 That is because we have all-too-often become accustomed to websites that improperly calculate timezones. 那是因为我们已经非常习惯于不正确计算时区的网站。

It would be much better to produce: 12:05:46 PM EDT for me and god-knows-what for other people. 这样做会更好:EDT对我来说是12:05:46 PM,对其他人来说,天知道。 Is this possible? 这可能吗?

To get the abbreviation in the output, pass timeZoneName: 'short' as one of the options. 要在输出中获得缩写,请传递timeZoneName: 'short'作为选项之一。 This will work in modern browsers that support the ECMAScript Internationalization API (ECMA-402). 这将在支持ECMAScript国际化API(ECMA-402)的现代浏览器中运行。

 var s = new Date().toLocaleTimeString(undefined, { timeZoneName: 'short' }); console.log(s); 

In the above, passing undefined for the locale tells the browser to use the users's current locale. 在上面,传递undefined的语言环境会告诉浏览器使用用户的当前语言环境。 If you wanted a specific locale, such as en-US , pass that instead. 如果您想要特定的语言环境(例如en-US ,请通过该方法。

You can read about all of the options for toLocaleTimeString in the MDN docs on the subject . 您可以在该主题的MDN文档中阅读有关toLocaleTimeString所有选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM