在 Javascript 中将 yyyy-mm-dd 转换为 UTC

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6273318/
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-10-25 20:07:15  来源:igfitidea点击:

Convert yyyy-mm-dd to UTC in Javascript

javascriptdatetimeutc

提问by Schneems

I need to convert a date in yyyy-mm-dd like 2011-12-30 to UTC using only javascript. How?

我需要仅使用 javascript 将 yyyy-mm-dd 中的日期(例如 2011-12-30)转换为 UTC。如何?

回答by alex

var utc = new Date('2011-12-30').toUTCString();

jsFiddle.

js小提琴

回答by Schneems

If you're having problems getting the other listed solution to work in firefox or safari you can use: http://www.datejs.com/

如果您在让其他列出的解决方案在 firefox 或 safari 中工作时遇到问题,您可以使用:http: //www.datejs.com/

myDate = new Date.parse("2011-12-30")
myUTCDate = Date.UTC(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds(), myDate.getMilliseconds());

Voila!!

瞧!!

回答by Dhiral Pandya

This is very simple method to convert String to Date in JavaScript

这是在 JavaScript 中将字符串转换为日期的非常简单的方法

var msomtDate = Date.parse('Here Your Date String'+' UTC',"yyyy/MM/dd HH:mm:ss");

回答by johnstorm

var toUTC = function (date) {
    var newDate = new Date();
    newDate.setTime(date.getTime() + (date.getTimezoneOffset() * 60 * 1000));
    return newDate;
};

console.log(toUTC(new Date('2011-12-30')));