Home > Web Front-end > JS Tutorial > How to Handle ASP.NET MVC JsonResult's Non-Standard Date Format in JavaScript?

How to Handle ASP.NET MVC JsonResult's Non-Standard Date Format in JavaScript?

DDD
Release: 2024-12-20 18:22:12
Original
297 people have browsed it

How to Handle ASP.NET MVC JsonResult's Non-Standard Date Format in JavaScript?

ASP.NET MVC JsonResult Date Format

When returning a JsonResult in ASP.NET MVC, you may encounter an issue where date properties are serialized in a format like "/Date(1239018869048)/". This format is not readable by JavaScript and can cause problems when handling dates in your application.

Solution 1: Manually Parse Date String in JavaScript

One approach is to parse the date string manually in JavaScript using the following code:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
Copy after login

This code removes the "Date(" and ")" characters from the string and converts it to a Date object.

Solution 2: Use JSON.parse() with a Reviver Function

Another option is to use the JSON.parse() function with a reviver function that converts the date string to a Date object. For example:

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

In this code, the reviver function checks if the value is a string and matches the "/Date((d*))/" pattern. If it does, the value is converted to a Date object using the Date constructor. Otherwise, the original value is returned.

Additional Considerations

It's important to note that the JSON specification does not define a standard date format. The "/Date(ticks)/" format used by ASP.NET MVC is a convention that allows JSON to represent a Date object.

When handling dates in JavaScript, you should consider the following:

  • The Date.parse() function can also be used to parse date strings, but it has some limitations.
  • You may need to specify the correct time zone when creating a Date object to ensure that dates are handled correctly.
  • ES6 introduced a new Date.toISOString() method that returns a date in the ISO 8601 format, which is a standard format recognized by many programming languages and applications.

The above is the detailed content of How to Handle ASP.NET MVC JsonResult's Non-Standard Date Format in JavaScript?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template