Created
February 6, 2012 17:40
-
-
Save benfoxall/1753574 to your computer and use it in GitHub Desktop.
A function for converting .NET dates in json responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* $.convertJSONDates | |
* | |
* $.getJSON(…).pipe($.convertJSONDates).done(function(data){…}) | |
* | |
* Based on … | |
* | |
* jQuery.parseJSON() | |
* http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html | |
* | |
* Copyright (c) 2011 Robert Koritnik | |
* Licensed under the terms of the MIT license | |
* http://www.opensource.org/licenses/mit-license.php | |
*/ | |
(function ($) { | |
// replacer RegExp | |
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i; | |
var dateNet = /\/Date\((\d+)(?:[-\+]\d+)?\)\//i; | |
var jsonDateConverter = function(value) { | |
if (typeof(value) === "string") | |
{ | |
if (dateISO.test(value)) | |
{ | |
return new Date(value); | |
} | |
if (dateNet.test(value)) | |
{ | |
return new Date(parseInt(dateNet.exec(value)[1], 10)); | |
} | |
} | |
return value; | |
}; | |
var converter = function(json){ | |
$.each(json || {}, function(k,v){ | |
if(typeof v == 'object'){ | |
if(v !== null){ | |
// recurse | |
converter(v); | |
} | |
} else { | |
json[k] = jsonDateConverter(v); | |
} | |
}); | |
return json; | |
}; | |
$.convertJSONDates = converter; | |
})(jQuery); |
Hi Sébastien,
Thanks for letting me know - I've updated this gist with your change.
Ben
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I receive an exception when I want to get json data with null values.
ex.: { name: "me", value: null }
I changed your converter to make it work.
var converter = function(json){
$.each(json, function(k,v){
if(typeof v == 'object'){
// recurse
if (v != null) {
converter(v);
}
}
else {
json[k] = jsonDateConverter(v);
}
});
return json;
};
Best Regards
Sébastien