Skip to content

Instantly share code, notes, and snippets.

@dustismo
Created August 31, 2011 16:54
Show Gist options
  • Save dustismo/1184051 to your computer and use it in GitHub Desktop.
Save dustismo/1184051 to your computer and use it in GitHub Desktop.
javascript ISO date parser
/**
* Parses an iso date.
*
* works with most (all?) iso format variations
* 2011-04-25T20:59:59.999-07:00
* 2011-04-25T20:59:59+07:00
* 2011-04-25T20:59:59Z
*
*/
Trendrr.parseISODate = function(string) {
// http://webcloud.se/log/JavaScript-and-ISO-8601/
//Fixed the incorrect escaping from the original blog post.
var regexp = "([0-9]{4})(\\-([0-9]{2})(\\-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(\\:([0-9]{2})(\\.([0-9]+))?)?" +
"(Z|(([\\-\\+])([0-9]{2})\\:?([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
if (d == null || d.length == 0) {
return null;
}
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
console.log(offset);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
return new Date(Number(time));
}
Trendrr.toDate = function(date) {
if (!date) {
return null;
}
if (date instanceof Date) {
return date;
}
//ISO date from above
var d = Trendrr.parseISODate(date);
if (d) {
return d;
}
//twitter date..
d = Date.parseExact(date, 'E, dd NNN yyyy HH:mm:ss Z');
if (d) {
return d;
}
return new Date(date *1000);
};
@dolmen
Copy link

dolmen commented Aug 31, 2011

Where is the testsuite?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment