Skip to content

Instantly share code, notes, and snippets.

@danielgreen
Last active March 8, 2021 22:26
Show Gist options
  • Save danielgreen/5670690 to your computer and use it in GitHub Desktop.
Save danielgreen/5670690 to your computer and use it in GitHub Desktop.
When an ASP.NET MVC 4 action returns JSON containing a DateTime value, the value is serialized into a format that cannot be natively understood by JavaScript. Here is some code to process the value into a JavaScript Date. A better solution than this is to use JSON.NET to serialize dates instead. See https://gist.github.com/danielgreen/5669903
function dateTimeReviver (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
}
$.ajax({
type: "GET",
cache: false,
url: "http://example.com/GetADate,
success: function (data) {
var parsedDate = JSON.parse(JSON.stringify(data.ExampleDate), dateTimeReviver);
alert(parsedDate); // Now we have a proper Date object
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment