Home > Web Front-end > JS Tutorial > How Can I Format Dates in ASP.NET MVC JSON Results?

How Can I Format Dates in ASP.NET MVC JSON Results?

Patricia Arquette
Release: 2024-12-10 16:15:18
Original
540 people have browsed it

How Can I Format Dates in ASP.NET MVC JSON Results?

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));
Copy after login

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;
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template