What is the “right” JSON date format?

前端 未结 16 1372
执念已碎
执念已碎 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:06

    "2014-01-01T23:28:56.782Z"

    The date is represented in a standard and sortable format that represents a UTC time (indicated by the Z). ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset:

    "2014-02-01T09:28:56.321-10:00"

    There are other variations of the timezone encoding in the ISO 8601 spec, but the –10:00 format is the only TZ format that current JSON parsers support. In general it’s best to use the UTC based format (Z) unless you have a specific need for figuring out the time zone in which the date was produced (possible only in server side generation).

    NB:

        var date = new Date();
        console.log(date); // Wed Jan 01 2014 13:28:56 GMT- 
        1000 (Hawaiian Standard Time) 
            
        var json = JSON.stringify(date);
        console.log(json);  // "2014-01-01T23:28:56.782Z"
    

    To tell you that's the preferred way even though JavaScript doesn't have a standard format for it

    // JSON encoded date
    var json = "\"2014-01-01T23:28:56.782Z\"";
    
    var dateStr = JSON.parse(json);  
    console.log(dateStr); // 2014-01-01T23:28:56.782Z
    

提交回复
热议问题