0

I know this is a very basic question, but I am stuck on this for several hours. Why do I get the wrong date and time, when I pass my ISO String to new Date()

new Date('2017-08-01T00:00:00');
=> 2017-07-31T22:00:00.000Z
eisbehr
  • 12,243
  • 7
  • 38
  • 63
William M.
  • 369
  • 1
  • 5
  • 10
  • 3
    This look like a timezone issue – Ulysse BN Aug 07 '18 at 12:02
  • Where's your time zone specification? – tehhowch Aug 07 '18 at 12:02
  • I get the value from an API which provides the ISO String without time zone specification. – William M. Aug 07 '18 at 12:04
  • Possible duplicate of [What are valid Date Time Strings in JavaScript?](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) – str Aug 07 '18 at 13:01
  • You should not use date time strings without time zones because not all current browsers handle those correctly. – str Aug 07 '18 at 13:08
  • 2017-08-01T00:00:00 is parsed as local (in compliant browsers) so represents a different moment in time in each system with a different offset. 2017-07-31T22:00:00.000Z is UTC, so your system timezone is likely UTC+0200. – RobG Aug 07 '18 at 13:33

2 Answers2

2
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

in your case, input date is not UTC and your system timezone is +0200 so you see the time difference. Second example shows there is no change in case of UTC.

Hope above examples clarify it.

Rajib Dey
  • 54
  • 4
-1

The returned date is an ISO 8601 date. This is the good date :)

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)
Xeewi
  • 39
  • 1
  • 7
  • 1
    The OP knows it's an ISO 8601 format string, the question is why is the result not what the OP expects. – RobG Aug 07 '18 at 13:37