以用户的语言环境格式和时间偏移显示日期/时间 [英] Display date/time in user's locale format and time offset

查看:25
本文介绍了以用户的语言环境格式和时间偏移显示日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望服务器始终在 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 日期开始的最简单的方法似乎是创建一个新的 Date 对象并使用 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

这篇关于以用户的语言环境格式和时间偏移显示日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆