Youtube's API returns a JSON object with an array of videos. Each video object has a published date formatted like "2012-01-11T20:49:59.415Z". If I initialize a Javascript Date object using the code below, the object returns "Invalid Date".
var dt = new Date( "2012-01-11T20:49:59.415Z" );
I'm using this on iOS/mobile Safari, if that makes a difference.
Any suggestions or ideas on how to create a valid object?
Youtube's API returns a JSON object with an array of videos. Each video object has a published date formatted like "2012-01-11T20:49:59.415Z". If I initialize a Javascript Date object using the code below, the object returns "Invalid Date".
var dt = new Date( "2012-01-11T20:49:59.415Z" );
I'm using this on iOS/mobile Safari, if that makes a difference.
Any suggestions or ideas on how to create a valid object?
Share Improve this question asked Jan 11, 2012 at 21:52 K. M. KroskiK. M. Kroski 1961 silver badge7 bronze badges5 Answers
Reset to default 4Try using JavaScript's Date.parse(string)
and the Date
constructor which takes the number of milliseconds since the epoch. The "parse" function should accept a valid ISO8601 date on any browser.
For example:
var d = new Date(Date.parse("2012-01-11T20:49:59.415Z"));
d.toString(); // => Wed Jan 11 2012 15:49:59 GMT-0500 (EST)
d.getTime(); // => 1326314999415
var dt = "2012-01-11T20:49:59.415Z".replace("T"," ").replace(/\..+/g,"")
dt = new Date( dt );
I ended up finding a solution at http://zetafleet./blog/javascript-dateparse-for-iso-8601. It looks like the date is in a format called 'ISO 8601.' On earlier browsers (Safari 4, Chrome 4, IE 6-8), ISO 8601 is not supported, so Date.parse doesn't work. The code referenced from the linked blog post extends the current Date class to support ISO 8601.
If you only need a portion of the date (eg. if you don't care about the time or time zone) you can just strip that portion of the date string off.
This page has code that parses youtube (ISO 8601) dates into a date object:
http://webcloud.se/log/JavaScript-and-ISO-8601/
Archive backup of same
It work for me, though I haven't tested it very much.