新的Date()返回错误的日期

时间:2018-08-07 12:00:42

标签: javascript date datetime datetime-format

我知道这是一个非常基本的问题,但是我坚持了几个小时。当我将ISO字符串传递给new Date()

时,为什么会得到错误的日期和时间?
new Date('2017-08-01T00:00:00');
=> 2017-07-31T22:00:00.000Z

2 个答案:

答案 0 :(得分:1)

new Date('2017-08-01T00:00:00').toISOString() => 2017-07-31T18:30:00.000Z  (my timezone is +530)
new Date('2017-08-01T00:00:00.000Z').toISOString() => 2017-08-01T00:00:00.000Z (input is in UTC)
new Date('2017-08-01T00:00:00.000+0530').toISOString() => 2017-07-31T18:30:00.000Z
new Date('2017-08-01T00:00:00.000+0200').toISOString() => 2017-07-31T22:00:00.000Z

在您的情况下,输入日期不是UTC,系统时区是+0200,因此您会看到时差。第二个示例显示,UTC不变。

希望以上示例对此加以说明。

答案 1 :(得分:0)

返回的日期是ISO 8601日期。 这是个好约会:)

const test = new Date('2017-08-01T00:00:00');
const isoString = test.toISOString()
const dateString = test.toDateString()

console.log('iso', isoString)
console.log('date', dateString)