What is the “right” JSON date format?

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

    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...
    

提交回复
热议问题