Javascript 将UTC转换为本地时间的Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13622142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:30:31  来源:igfitidea点击:

Javascript to convert UTC to local time

javascriptdatetime

提问by lannyboy

Okay, say JSON parse string UTC date as below:

好的,说 JSON 解析字符串 UTC 日期如下:

2012-11-29 17:00:34 UTC

Now if I want to convert this UTC date to my local time, how can I do this?

现在,如果我想将此 UTC 日期转换为我的本地时间,我该怎么做?

How do I format it to something else like yyyy-MM-dd HH:mm:ss z?

如何将其格式化为其他格式yyyy-MM-dd HH:mm:ss z

This date.toString('yyyy-MM-dd HH:mm:ss z');never work out :/

date.toString('yyyy-MM-dd HH:mm:ss z');永远不会解决:/

回答by ajtrichards

Try:

尝试:

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();

回答by Surabhi

var offset = new Date().getTimezoneOffset();

offsetwill be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.

offset将是从本地时间到 UTC 的时间间隔(以分钟为单位)。要从 UTC 日期获取当地时间,您需要从日期中减去分钟数。

utc_date.setMinutes(utc_date.getMinutes() - offset);

回答by user2645663

To format your date try the following function:

要格式化您的日期,请尝试以下功能:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standardfunction, which is not working in Chrome, but working in FF (afaik).

但这样做的缺点是,它是一个非标准功能,在 Chrome 中不起作用,但在 FF (afaik) 中起作用。

Chris

克里斯

回答by Murali Prasanth

This should work

这应该工作

var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()

回答by Khaled Al-Ansari

The solutions above are right but might crash in FireFox and Safari! and that's what webility.jsis trying to solve. Check the toUTCfunction, it works on most of the main browers and it returns the time in ISO format

上面的解决方案是正确的,但可能会在 FireFox 和 Safari 中崩溃!这就是webility.js试图解决的问题。检查toUTC功能,它适用于大多数主要浏览器,并以 ISO 格式返回时间

回答by Penny Liu

You could take a look at date-and-timeapi for easily date manipulation.

您可以查看date-and-timeapi 以轻松进行日期操作。

let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>

回答by user3856049

/*
 * convert server time to local time
 *  simbu
*/
function convertTime(serverdate) {
    var date = new Date(serverdate);
    // convert to utc time
    var toutc = date.toUTCString();
    //convert to local time
    var locdat = new Date(toutc + " UTC");
    return locdat;
}