2

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?

markreyes
  • 1,249
  • 1
  • 13
  • 27
  • What is .getTimezoneOffset() giving you in safari vs everywhere else? – AndrewG Apr 25 '18 at 18:46
  • I have Safari's web console open and plopped a console.log to see but I get nothing. Whereas other browsers are returning a value of 420. I can't connect the dots on this one. MDN says this method is supported in Safari: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset – markreyes Apr 25 '18 at 19:01
  • "2018-04-25T13:36:00" isn't UTC, it should be parsed as local. So your function is actually treating a local date as UTC, not the other way around. And yes, there's a bug in Safari's parser. – RobG Apr 26 '18 at 00:33

1 Answers1

5

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());
RobG
  • 142,382
  • 31
  • 172
  • 209