What is the “right” JSON date format?

前端 未结 16 1594
执念已碎
执念已碎 2020-11-21 15:14

I\'ve seen so many different standards for the JSON date format:

\"\\\"\\\\/Date(1335205592410)\\\\/\\\"\"         .NET JavaScriptSerializer
\"\\\"\\\\/Date(         


        
16条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 16:14

    I think that really depends on the use case. In many cases it might be more beneficial to use a proper object model (instead of rendering the date to a string), like so:

    {
    "person" :
          {
     "name" : {
       "first": "Tom",
       "middle": "M",
      ...
    }
     "dob" :  {
             "year": 2012,
             "month": 4,
             "day": 23,
             "hour": 18,
             "minute": 25,
             "second": 43,
             "timeZone": "America/New_York"
        }   
       }
    }
    

    Admittedly this is more verbose than RFC 3339 but:

    • it's human readable as well
    • it implements a proper object model (as in OOP, as far as JSON permits it)
    • it supports time zones (not just the UTC offset at the given date and time)
    • it can support smaller units like milliseconds, nanoseconds, ... or simply fractional seconds
    • it doesn't require a separate parsing step (to parse the date-time string), the JSON parser will do everything for you
    • easy creation with any date-time framework or implementation in any language
    • can easily be extended to support other calendar scales (Hebrew, Chinese, Islamic ...) and eras (AD, BC, ...)
    • it's year 10000 safe ;-) (RFC 3339 isn't)
    • supports all-day dates and floating times (Javascript's Date.toJSON() doesn't)

    I don't think that correct sorting (as noted by funroll for RFC 3339) is a feature that's really needed when serializing a date to JSON. Also that's only true for date-times having the same time zone offset.

提交回复
热议问题