ASP.NET MVC JsonResult Date Formatting
In ASP.NET MVC, when returning a JsonResult containing a model with a date property, the default behavior is for the date to be serialized in the "/Date(ticks)/" format. However, this may not always be the desired format for consuming applications.
To handle the "/Date(ticks)/" format in JavaScript, there are several options:
Parse the String
One approach is to parse the serialized date string using string manipulation:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
Reviver Function in JSON.parse()
When using JSON.parse(), you can specify a reviver function to modify the parsed values before they are returned. For example, to convert "/Date(ticks)/" strings to JavaScript dates:
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; });
The above is the detailed content of How Can I Format Dates in ASP.NET MVC's JsonResult to Avoid the '/Date(ticks)/' Format?. For more information, please follow other related articles on the PHP Chinese website!