ASP.NET MVC JsonResult Date Format
When returning a JsonResult in ASP.NET MVC, you may encounter an issue where date properties are serialized in a format like "/Date(1239018869048)/". This format is not readable by JavaScript and can cause problems when handling dates in your application.
Solution 1: Manually Parse Date String in JavaScript
One approach is to parse the date string manually in JavaScript using the following code:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
This code removes the "Date(" and ")" characters from the string and converts it to a Date object.
Solution 2: Use JSON.parse() with a Reviver Function
Another option is to use the JSON.parse() function with a reviver function that converts the date string to a Date object. For example:
var parsed = JSON.parse(data, function(key, value) { if (typeof value === 'string') { var d = /\/Date\((\d*)\)\//.exec(value); return (d) ? new Date(+d[1]) : value; } return value; });
In this code, the reviver function checks if the value is a string and matches the "/Date((d*))/" pattern. If it does, the value is converted to a Date object using the Date constructor. Otherwise, the original value is returned.
Additional Considerations
It's important to note that the JSON specification does not define a standard date format. The "/Date(ticks)/" format used by ASP.NET MVC is a convention that allows JSON to represent a Date object.
When handling dates in JavaScript, you should consider the following:
The above is the detailed content of How to Handle ASP.NET MVC JsonResult's Non-Standard Date Format in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!