Home > Web Front-end > JS Tutorial > How Can I Format Dates in ASP.NET MVC's JsonResult to Avoid the '/Date(ticks)/' Format?

How Can I Format Dates in ASP.NET MVC's JsonResult to Avoid the '/Date(ticks)/' Format?

Susan Sarandon
Release: 2024-12-10 22:38:09
Original
662 people have browsed it

How Can I Format Dates in ASP.NET MVC's JsonResult to Avoid the

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

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

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!

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