Home >Web Front-end >JS Tutorial >How to Handle Date Formatting in ASP.NET MVC JsonResult?

How to Handle Date Formatting in ASP.NET MVC JsonResult?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 12:44:09155browse

How to Handle Date Formatting in ASP.NET MVC JsonResult?

ASP.NET MVC JsonResult Date Format

When returning a JsonResult from an ASP.NET MVC controller, date properties in the model will appear in a JavaScript-specific format:

"\/Date(1239018869048)\/"

JSON and Date Values

The JSON specification does not define a specific representation for dates. Thus, custom handling is required.

Handling the Date Format in JavaScript

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;
});

Changing the Serializer Output

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!

Statement:
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