将 UTC 日期时间转换为本地日期时间 [英] Convert UTC date time to local date time

查看:51
本文介绍了将 UTC 日期时间转换为本地日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器得到一个日期时间变量,格式如下:6/29/2011 4:52:48 PM,它是 UTC 时间.我想使用 JavaScript 将其转换为当前用户的浏览器时区.

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.

如何使用 JavaScript 或 jQuery 做到这一点?

How this can be done using JavaScript or jQuery?

推荐答案

在我看来,服务器在一般情况下应始终以标准化 ISO 8601 格式返回日期时间.

In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.

更多信息在这里:

在这种情况下,服务器将返回 '2011-06-29T16:52:48.000Z',这将直接输入 JS Date 对象.

IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.

var utcDate = '2011-06-29T16:52:48.000Z';  // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);

localDate 将是正确的本地时间,在我的情况下是两个小时后(DK 时间).

The localDate will be in the right local time which in my case would be two hours later (DK time).

真的不必进行所有这些只会使事情复杂化的解析,只要您与服务器期望的格式一致.

You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.

这篇关于将 UTC 日期时间转换为本地日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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