如何假设新日期(YYYY-MM-DD)输入是UTC日期

时间:2018-01-31 21:16:46

标签: javascript date

我需要从格式为Date的UTC日期字符串生成javascript YYYY-MM-DD。这是一个例子:

var date = new Date('2018-01-31');

创建的日期是:

  

Tue Jan 30 2018 19:00:00 GMT-0500(东部标准时间)

鉴于时区偏移,日期是昨天。

如何创建一个javascript日期,假设永恒的输入是UTC?

2 个答案:

答案 0 :(得分:4)

您可以使用Date.UTC 这是https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

的示例
var utcDate1 = new Date(Date.UTC(96, 1, 2, 3, 4, 5));
var utcDate2 = new Date(Date.UTC(0, 0, 0, 0, 0, 0));

console.log(utcDate1.toUTCString());
// expected output: Fri, 02 Feb 1996 03:04:05 GMT

console.log(utcDate2.toUTCString());
// expected output: Sun, 31 Dec 1899 00:00:00 GMT

所以你得到这个解决方案:

var test = "2018-01-31";
var year = test.substr(0,4);
var month =  test.substr(5,2) -1;
var day =  test.substr(8,2);

var utcDate1 = new Date(Date.UTC(year,month,day));
alert(utcDate1.toUTCString());
// expected output:Wed, 31 Jan 2018 00:00:00 GMT

答案 1 :(得分:2)

您可以结合使用Date.UTCsplitspread operator syntax (... is not an operator)



var convertedDate = '2018-01-31'.split('-');
convertedDate[1] = convertedDate[1] - 1 // Date.UTC expects a value from 0-11

var date = new Date(Date.UTC(...convertedDate))
console.log(date.toDateString());




值得注意的是,Date.UTC预计月份为0-11(由于某种原因)