Reputation: 1289
I have a UTC string "2018-04-25T13:36:00"
which I pass into this function:
function convertUTCDateToLocalDate(dateString) {
var newDate = new Date(dateString);
newDate.setMinutes(dateString.getMinutes() - dateString.getTimezoneOffset());
return newDate;
}
var localDate = convertUTCDateToLocalDate(new Date("2018-04-25T13:36:00"));
console.log(localDate);
Chrome, Firefox and Edge returns correctly as (PASS):
Wed Apr 25 2018 06:36:00 GMT-0700 (PDT)
However, Safari returns it as (FAIL):
Tue Apr 24 2018 23:36:00 GMT-0700 (PDT)
Why is Safari being a stickler?
Upvotes: 2
Views: 7836
Reputation: 147363
The string "2018-04-25T13:36:00" should be parsed as local, however Safari gets it wrong and parses it as UTC. Since you want to parse it as UTC, one simple (but not recommended) method is to simply add "Z" to the string so all browsers parse it as UTC:
var s = '2018-04-25T13:36:00';
console.log(new Date(s+'Z').toString());
However, general advice is never use the built-in parser as it is notoriously problematic (see Why does Date.parse give incorrect results?), write your own parser for your particular format or use a library. To parse your format as UTC, consider:
var s = '2018-04-25T13:36:00';
// Parse YYYY-MM-DDTHH:mm:ss as UTC
function parseUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],--b[1],b[2],b[3],b[4],b[5]))
}
var d = parseUTC(s);
console.log(d.toISOString());
console.log(d.toString());
Upvotes: 6