ASP.NET MVC JsonResult Date Format

前端 未结 25 3299
渐次进展
渐次进展 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: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

提交回复
热议问题