Home >Web Front-end >JS Tutorial >How to Handle Date Formatting in ASP.NET MVC JsonResult?
When returning a JsonResult from an ASP.NET MVC controller, date properties in the model will appear in a JavaScript-specific format:
"\/Date(1239018869048)\/"
The JSON specification does not define a specific representation for dates. Thus, custom handling is required.
Option 1: Parsing the Format
Manually parse the date string using the following code:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
Option 2: Using a JSON.parse() Reviver
Utilize the reviver function parameter in JSON.parse() to intercept and transform string representations of 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; });
It is also possible to modify the serializer settings to output dates in the desired format (e.g., "new Date(1239018869048)"). However, this involves delving into the underlying serialization mechanisms.
The above is the detailed content of How to Handle Date Formatting in ASP.NET MVC JsonResult?. For more information, please follow other related articles on the PHP Chinese website!