Skip to content

Instantly share code, notes, and snippets.

@pepe84
Created November 17, 2011 13:27
Show Gist options
  • Save pepe84/1373125 to your computer and use it in GitHub Desktop.
Save pepe84/1373125 to your computer and use it in GitHub Desktop.
JavaScript ISO 8601 date
/**
* ISO 8601 date
* @see http://webcloud.se/log/JavaScript-and-ISO-8601/
* @example "2008-07-09T16:13:30+12:00"
*/
function IsoDate() {};
// Date inheritance
IsoDate.prototype = new Date();
// Public methods
/**
* Set date parsing ISO 8601 format
*
* @param iso String
*/
IsoDate.prototype.parse = function iso_date_parse(iso) {
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 = iso.match(new RegExp(regexp));
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]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
var time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
};
// Static methods
/**
* Exports to ISO 8601 format
*
* @return String
*/
IsoDate.toIsoString = function iso_date_to_iso_string(date) {
function pad(n) {
return n < 10 ? '0' + n : n
}
function offset(n) {
return n < 0 ? '-' + pad(n * -1) : '+' + pad(n);
}
return date.getUTCFullYear() + '-'
+ pad(date.getUTCMonth()) + '-'
+ pad(date.getUTCDate()) + 'T'
+ pad(date.getUTCHours()) + ':'
+ pad(date.getUTCMinutes()) + ':'
+ pad(date.getUTCSeconds())
+ offset(date.getTimezoneOffset()/60) + ':00';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment