ASP.NET MVC JsonResult Date Format

前端 未结 25 3250
渐次进展
渐次进展 2020-11-21 11:22

I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonRes         


        
25条回答
  •  甜味超标
    2020-11-21 11:39

    Just to expand on casperOne's answer.

    The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal "/" is the same as "\/", and a string literal will never get serialized to "\/" (even "\/" must be mapped to "\\/").

    See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to "From JavaScript Literals to JSON")

    One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft's ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as "\/Date(628318530718)\/".

    A solution would be to just parse it out:

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

    However I've heard that there is a setting somewhere to get the serializer to output DateTime objects with the new Date(xxx) syntax. I'll try to dig that out.


    The second parameter of JSON.parse() accepts a reviver function where prescribes how the value originally produced by, before being returned.

    Here is an example for date:

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

    See the docs of JSON.parse()

提交回复
热议问题