Search code examples
javascriptdatetimeiso

JavaScript time is an hour behind after ISO conversion


I create a new Date in JavaScript, with the correct time, but after I use toISOString() to convert it, it's an hour behind. Why would that be?

https://jsfiddle.net/73nfyxeL/

var createdDateTime = new Date('2015-04-01 11:53:00');
var isoCreatedDateTime = "";

alert(createdDateTime);
isoCreatedDateTime = createdDateTime.toISOString().match(/(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})/);
alert(isoCreatedDateTime[1] + ' ' + isoCreatedDateTime[2]);
createdDateTime.setMinutes(createdDateTime.getMinutes() + 1);

As far as I'm aware this should be immune to changes to the local time (eg. daylight savings), as I'm giving it a pre-set time, and not a timezone. What's going on?


Solution

  • The toISOString method doesn't only format the date, first it is converted to UTC.

    The difference between your local time zone and UTC is one hour.