ASP.NET MVC JsonResult Date Format

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

    Here's my solution in Javascript - very much like JPot's, but shorter (and possibly a tiny bit faster):

    value = new Date(parseInt(value.substr(6)));
    

    "value.substr(6)" takes out the "/Date(" part, and the parseInt function ignores the non-number characters that occur at the end.

    EDIT: I have intentionally left out the radix (the 2nd argument to parseInt); see my comment below. Also, please note that ISO-8601 dates are preferred over this old format -- so this format generally shouldn't be used for new development. See the excellent Json.NET library for a great alternative that serializes dates using the ISO-8601 format.

    For ISO-8601 formatted JSON dates, just pass the string into the Date constructor:

    var date = new Date(jsonDate); //no ugly parsing needed; full timezone support
    

提交回复
热议问题