What is the “right” JSON date format?

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

    The following code has worked for me. This code will print date in DD-MM-YYYY format.

    DateValue=DateValue.substring(6,8)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(0,4);
    

    else, you can also use:

    DateValue=DateValue.substring(0,4)+"-"+DateValue.substring(4,6)+"-"+DateValue.substring(6,8);
    
    0 讨论(0)
  • 2020-11-21 16:05

    From RFC 7493 (The I-JSON Message Format ):

    I-JSON stands for either Internet JSON or Interoperable JSON, depending on who you ask.

    Protocols often contain data items that are designed to contain timestamps or time durations. It is RECOMMENDED that all such data items be expressed as string values in ISO 8601 format, as specified in RFC 3339, with the additional restrictions that uppercase rather than lowercase letters be used, that the timezone be included not defaulted, and that optional trailing seconds be included even when their value is "00". It is also RECOMMENDED that all data items containing time durations conform to the "duration" production in Appendix A of RFC 3339, with the same additional restrictions.

    0 讨论(0)
  • 2020-11-21 16:06

    JSON itself has no date format, it does not care how anyone stores dates. However, since this question is tagged with javascript, I assume you want to know how to store javascript dates in JSON. You can just pass in a date to the JSON.stringify method, and it will use Date.prototype.toJSON by default, which in turns uses Date.prototype.toISOString (MDN on Date.toJSON):

    const json = JSON.stringify(new Date());
    const parsed = JSON.parse(json); //2015-10-26T07:46:36.611Z
    const date = new Date(parsed); // Back to date object
    

    I also found it useful to use the reviver parameter of JSON.parse (MDN on JSON.parse) to automatically convert ISO strings back to javascript dates whenever I read JSON strings.

    const isoDatePattern = new RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);
    
    const obj = {
     a: 'foo',
     b: new Date(1500000000000) // Fri Jul 14 2017, etc...
    }
    const json = JSON.stringify(obj);
    
    // Convert back, use reviver function:
    const parsed = JSON.parse(json, (key, value) => {
        if (typeof value === 'string' &&  value.match(isoDatePattern)){
            return new Date(value); // isostring, so cast to js date
        }
        return value; // leave any other value as-is
    });
    console.log(parsed.b); // // Fri Jul 14 2017, etc...
    
    0 讨论(0)
  • 2020-11-21 16:06

    I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:

    { "myDateField": { "$date" : <ms-since-epoch> } }

    As described here: https://docs.meteor.com/api/ejson.html

    Benefits

    1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
    2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
    3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

    Conclusion

    I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 16:07

    JSON does not know anything about dates. What .NET does is a non-standard hack/extension.

    I would use a format that can be easily converted to a Date object in JavaScript, i.e. one that can be passed to new Date(...). The easiest and probably most portable format is the timestamp containing milliseconds since 1970.

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