以用户区域设置格式显示日期/时间和时间偏移

我希望服务器始终以HTML中的UTC形式提供日期,并让客户端站点上的JavaScript将其转换为用户的本地时区。

如果我能以用户的区域设置日期格式输出,则为奖励。

回答:

以UTC日期开头的最简单的方法似乎是创建一个新Date对象,并使用这些setUTC…方法将其设置为所需的日期/时间。

然后,各种toLocale…String方法将提供本地化输出。

例:

// 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

以上是 以用户区域设置格式显示日期/时间和时间偏移 的全部内容, 来源链接: utcz.com/qa/402340.html

回到顶部