显示用户区域设置格式和时间偏移量的日期/时间 [英] Display date/time in user's locale format and time offset
本文介绍了显示用户区域设置格式和时间偏移量的日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望服务器始终以HTML格式在UTC中提供日期,客户端上的JavaScript将其转换为用户的本地时区。
I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
可以以用户的地区日期格式输出。
Bonus if I can output in the user's locale date format.
推荐答案
看起来最愚蠢的UTC开始时间是创建一个新的日期
对象,并使用 setUTC ...
方法将其设置为所需的日期/时间。
Seems the most foolproof way to start with a UTC date is to create a new Date
object and use the setUTC…
methods to set it to the date/time you want.
然后各种 toLocale ... String
方法将提供本地化的输出。
Then the various toLocale…String
methods will provide localized output.
// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString()); // -> 02/28/2004
console.log(d.toLocaleTimeString()); // -> 23:45:26
- toLocaleString
- toLocaleDateString
- toLocaleTimeString
- getTimezoneOffset
这篇关于显示用户区域设置格式和时间偏移量的日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文