5
votes

I can create a JavaScript date object with:

var d=new Date('2012-08-07T07:47:46Z');
document.write(d);

This will write the date using the browser's time zone. But I should be able to do (no 'Z'):

var d=new Date('2012-08-07T07:47:46');
document.write(d);

This returns the same as above, but according to the ISO8601 standard, a string without a timezone (e.g. +01:00) and without 'Z', the date should be considered in the local time zone. So the second example above should write the datetime as 7:47am.

I am getting a datetime string from a server and I want to display exactly that datetime. Any ideas?

2

2 Answers

6
votes

I found this script works well. It extends the Date.parse method.

https://github.com/csnover/js-iso8601/

Date.parse('2012-08-07T07:47:46');

It doesn't work on the new Date() constructor however.

-1
votes

You are right, Javascript doesn't play well with the ISO8601.

Use this function to convert to the desired format:

function ISODateString(d) {
  function pad(n){
    return n<10 ? '0'+n : n
  }
  return d.getUTCFullYear()+'-'
  + pad(d.getUTCMonth()+1)+'-'
  + pad(d.getUTCDate())+'T'
  + pad(d.getUTCHours())+':'
  + pad(d.getUTCMinutes())+':'
  + pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
print(ISODateString(d));

Taken from: Mozilla