ASP.NET MVC JsonResult Date Format

前端 未结 25 3289
渐次进展
渐次进展 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()

    0 讨论(0)
  • 2020-11-21 11:40

    Using jQuery to auto-convert dates with $.parseJSON

    Note: this answer provides a jQuery extension that adds automatic ISO and .net date format support.

    Since you're using Asp.net MVC I suspect you're using jQuery on the client side. I suggest you read this blog post that has code how to use $.parseJSON to automatically convert dates for you.

    Code supports Asp.net formatted dates like the ones you mentioned as well as ISO formatted dates. All dates will be automatically formatted for you by using $.parseJSON().

    0 讨论(0)
  • 2020-11-21 11:42

    The better way to handle dates in knockoutjs is to use moment library and handle dates like boss. You can easily deal with dates like /Date(-62135578800000)/. No need to bother of how your serialize date in controller.

    function jsonToDate(date,format) {
       return moment(date).format(format);
    }
    

    use it like

    var formattedDate = jsonToDate(date,'MM/DD/YYYY')
    

    momentjs supports lots of date time formats and utility functions on dates.

    0 讨论(0)
  • 2020-11-21 11:43

    Annoying, isn't it ?

    My solution was to change my WCF service to get it to return DateTimes in a more readable (non-Microsoft) format. Notice below, the "UpdateDateOriginal", which is WCF's default format of dates, and my "UpdateDate", which is formatted to something more readable.

    Here's how to do it:

    Changing WCF date format

    Hope this helps.

    0 讨论(0)
  • 2020-11-21 11:43

    The easiest one:

    var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
    Var newDate = new Date(milisegundos).toLocaleDateString("en-UE");

    0 讨论(0)
  • 2020-11-21 11:45

    Ajax communication between the client and the server often involves data in JSON format. While JSON works well for strings, numbers and Booleans it can pose some difficulties for dates due to the way ASP.NET serializes them. As it doesn't have any special representation for dates, they are serialized as plain strings. As a solution the default serialization mechanism of ASP.NET Web Forms and MVC serializes dates in a special form - /Date(ticks)/- where ticks is the number of milliseconds since 1 January 1970.

    This problem can be solved in 2 ways:

    client side

    Convert the received date string into a number and create a date object using the constructor of the date class with the ticks as parameter.

    function ToJavaScriptDate(value) {
      var pattern = /Date\(([^)]+)\)/;
      var results = pattern.exec(value);
      var dt = new Date(parseFloat(results[1]));
      return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }
    

    server side

    The previous solution uses a client side script to convert the date to a JavaScript Date object. You can also use server side code that serializes .NET DateTime instances in the format of your choice. To accomplish this task you need to create your own ActionResult and then serialize the data the way you want.

    reference : http://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html

    0 讨论(0)
提交回复
热议问题