Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a Youtube API Date in Javascript

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?

like image 588
K. M. Kroski Avatar asked Jan 11 '12 21:01

K. M. Kroski


3 Answers

Try 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
like image 57
maerics Avatar answered Nov 06 '22 16:11

maerics


var dt = "2012-01-11T20:49:59.415Z".replace("T"," ").replace(/\..+/g,"")
dt = new Date( dt );
like image 23
Ivan Castellanos Avatar answered Nov 06 '22 17:11

Ivan Castellanos


I ended up finding a solution at http://zetafleet.com/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.

like image 3
K. M. Kroski Avatar answered Nov 06 '22 16:11

K. M. Kroski