ASP.NET MVC JSON Result Date Format
When returning a JsonResult object, it's common to encounter issues with date formatting. By default, ASP.NET MVC serializes DateTime values as "/Date(ticks)/", where 'ticks' represents milliseconds since the Unix epoch (January 1, 1970 UTC).
Solution
To resolve this, there are several approaches:
1. Use the New Date(xxx) Syntax
By default, the ASP.NET MVC serializer emits dates in the "/Date(ticks)/" format. However, you can configure the serializer to use the "new Date(xxx)" syntax by setting the "DateFormatString" property on the "DateConverter" class to "yyyy-MM-ddTHH:mm:ss" (or any other desired format). This will cause the serializer to output dates in the "new Date()" format.
2. Parse and Convert Manually
Alternatively, you can manually parse the "/Date(ticks)/" string and convert it to a Date object:
value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
3. Use a Reviver Function
Another option is to use a "reviver" function when parsing the JSON data:
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; });
By using one of the mentioned approaches, you can handle dates in your JsonResult objects and display them in the desired format.
The above is the detailed content of How Can I Format Dates in ASP.NET MVC JSON Results?. For more information, please follow other related articles on the PHP Chinese website!