0

I have this problem. I have this date with this format

var datestring = "2017-10-30T15:03:10.933044Z";

If I write my code like this

var d = new Date(datestring);

I obtaine

Mon Oct 30 2017 16:03:10 GMT+0100 (ora solare Europa occidentale)

because there is one hour of a daylight in italy now. Nevertheless, I would like to have the same hour of 'datestring' (15, and not 16). Could you help me?

thank you very much

Raul
  • 115
  • 5
  • 16

2 Answers2

1

Your input string is in ISO-8601 format. In this format, the Z at the end means the timestamp is UTC-based.

You can obtain a more human-friendly UTC-based string representation with the .toUTCString() method.

var datestring = "2017-10-30T15:03:10.933044Z";
var d = new Date(datestring);
var s = d.toUTCString();
console.log(s) // "Mon, 30 Oct 2017 15:03:10 GMT"

If you want the string in a specific format, then consider using a library like Moment.js.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
1

According to ECMA-262, if you want to treat an ISO 8601 format UTC timestamp as local, just remove the Z. However, it will now represent a different moment in time if the local timezone is not GMT+0000.

Also, using the built-in parser is not recommended (see Why does Date.parse give incorrect results?), as some browsers will still treat it as UTC (e.g. Safari 11) or perhaps invalid. You should either write your own function to parse the string, or use a library. There are plenty of good parsing and formatting libraries available.

var s = '2017-10-30T15:03:10.933044Z';
var d = new Date(s.replace(/z/i,''));
console.log(d.toString());
RobG
  • 142,382
  • 31
  • 172
  • 209