Skip to content

Instantly share code, notes, and snippets.

@FrostyZoob
Created October 15, 2012 18:09
Show Gist options
  • Save FrostyZoob/3894073 to your computer and use it in GitHub Desktop.
Save FrostyZoob/3894073 to your computer and use it in GitHub Desktop.
Automatic ISO 8601 conversion in Javascript
$.ajaxSetup({
converters: { "text json": function (jsonString) {
var res = JSON.parseWithDate(jsonString);
if (res && res.hasOwnProperty("d"))
res = res.d;
return res;
} }
});
/*
Ripped from ServiceProxy.js
Version 0.981 - 4/5/11
(c) 2008-2011 Rick Strahl, West Wind Technologies
www.west-wind.com
Licensed under MIT License
http://en.wikipedia.org/wiki/MIT_License
*/
if (this.JSON && !this.JSON.parseWithDate) {
//Original reISO regex replaced with one pulled from XDate.js
var reISO = /^(\d{4})(-(\d{2})(-(\d{2})([T ](\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|(([-+])(\d{2})(:?(\d{2}))?))?)?)?)?$/
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.parseWithDate = function (json) {
/// <summary>
/// parses a JSON string and turns ISO or MSAJAX date strings
/// into native JS date objects
/// </summary>
/// <param name="json" type="var">json with dates to parse</param>
/// </param>
/// <returns type="value, array or object" />
try {
var res = JSON.parse(json,
function (key, value) {
if (typeof value === 'string') {
var a = reISO.exec(value);
if (a) {
var d = new Date(Date.UTC(
a[1],
a[3] ? a[3] - 1 : 0,
a[5] || 1,
a[7] || 0,
a[8] || 0,
a[10] || 0,
a[12] ? Number('0.' + a[12]) * 1000 : 0
));
if (a[13]) { // has gmt offset or Z
if (a[14]) { // has gmt offset
d.setUTCMinutes(
d.getUTCMinutes() + (a[15] == '-' ? 1 : -1) * (Number(a[16]) * 60 + (a[18] ? Number(a[18]) : 0))
);
}
}
return d;
}
a = reMsAjax.exec(value);
if (a) {
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
}
return value;
});
return res;
} catch (e) {
// orignal error thrown has no error message so rethrow with message
throw new Error("JSON content could not be parsed");
return null;
}
};
JSON.dateStringToDate = function (dtString) {
/// <summary>
/// Converts a JSON ISO or MSAJAX string into a date object
/// </summary>
/// <param name="" type="var">Date String</param>
/// <returns type="date or null if invalid" />
var a = reISO.exec(dtString);
if (a) {
var d = new Date(Date.UTC(
a[1],
a[3] ? a[3] - 1 : 0,
a[5] || 1,
a[7] || 0,
a[8] || 0,
a[10] || 0,
a[12] ? Number('0.' + a[12]) * 1000 : 0
));
if (a[13]) { // has gmt offset or Z
if (a[14]) { // has gmt offset
d.setUTCMinutes(
d.getUTCMinutes() + (a[15] == '-' ? 1 : -1) * (Number(a[16]) * 60 + (a[18] ? Number(a[18]) : 0))
);
}
}
return d;
}
a = reMsAjax.exec(dtString);
if (a) {
var b = a[1].split(/[-,.]/);
return new Date(+b[0]);
}
return null;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment