1

I have a table that contains DateTimes in UTC. I'm using PHP to return these date/time strings to an AJAX request in JSON. An example of one of these strings I am receiving on the front end is "2014-12-22 09:36:54". I would like to display this to the user in their local time. For instance I am 8 hours behind UTC time in California, so I would like to see something like "2014-12-22 01:36:54".

In javascript I tried new Date("2014-12-22T09:36:54").toLocaleString() and got "12/22/2014, 9:36:54 AM"---basically an unchanged date/time.

I tried new Date("2014-12-22T09:36:54").toUTCString() and I got "Mon, 22 Dec 2014 17:36:54 GMT", which is pretty much the opposite of what I wanted. But I guess that should have been obvious.

Last thoughts...:

Am I going to have to do some manipulation involving getTimezoneOffset()?

Would this be easier solved on the PHP backend?

One last note is that I included jstz.js thinking it would help but all it does is return the timezone name, and I don't know how that is particularly useful. Does any function take the name of a timezone as an argument which would be helpful in this situation?

Brimby
  • 847
  • 8
  • 25
  • 1
    JavaScript is notoriously hard to use when it comes to dates and times. If you can solve it with PHP, do that instead and save yourself the headache. – Daniel Weiner Jan 20 '15 at 23:13
  • see http://stackoverflow.com/a/439871/65387 – mpen Jan 20 '15 at 23:14
  • i don't see what lib or tool can help; if you don't have the timezone in the input, there's nothing you can do to magically invent it. if you have a valid date, it will be shown in the correct time using toLocaleString – dandavis Jan 20 '15 at 23:14

1 Answers1

0

To reliably convert a UTC string like "2014-12-22 09:36:54" to local, manually parse it, e.g.:

function parseISOAsLocal(s) {
  var b = s.split(/\D/);
  return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}

An ISO 8601 compliant string without a timezone must be treated as UTC according to the current ECMA-262 standard (ed5). However, the draft version 6 changes that to treat them as local (per ISO 8601). Most browsers treat it as UTC, however Chrome treats it as local (and IE 8 as NaN). Much better to manually parse date strings and avoid browser vagaries.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • 2
    Cool, another down voter too lazy to bother with an explanation or provide an alternative answer. – RobG Jan 21 '15 at 22:58