Skip to content

Instantly share code, notes, and snippets.

@listochkin
Created February 9, 2012 09:42
Show Gist options
  • Save listochkin/1778901 to your computer and use it in GitHub Desktop.
Save listochkin/1778901 to your computer and use it in GitHub Desktop.
Date support for jQuery json and jsonp calls.
// Copyright (c) 2012 Andrey Listochkin
// This code is freely distributable under the MIT license:
// http://www.opensource.org/licenses/mit-license.php
// put this file after jQuery and before any $.ajax calls
(function($) {
if (!window.JSON) {
$.error( "No JSON available, add json2.js to your project from https://github.com/douglascrockford/JSON-js/blob/master/json2.js" );
}
// fix for old browsers.
// toISOString returns the same result in all browsers
if (typeof Date.prototype.toISOString !== 'function') {
Date.prototype.toISOString = Date.prototype.toJSON
}
// jQuery should parse dates coming from server
$.fn.parseJSON = function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim( data );
return window.JSON.parse( data, function (key, value) {
var a;
if (typeof value === 'string') {
a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment