How to use JSON.parse reviver parameter to parse date string

后端 未结 6 797
醉酒成梦
醉酒成梦 2020-12-09 07:20

My JSON string contains a date field that returns such a value:

\"2009-04-04T22:55:16.0000000-04:00\"

I am particularly interested in parsi

6条回答
  •  暖寄归人
    2020-12-09 07:28

    The use of return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));

    does not adjust the date for the timezone information, the -4:00 in the example.

    An alternative is to let Date() do the parsing for you:

    var dateReviver = function (key, value) {
        var a;
        if (typeof value === 'string') {
            a = Date.parse(value);
            if (a) {
                return new Date(a);
            }    
        }
        return value;
    }
    

    If the JSON had been formatted with JSON.stringify() it would have been in UTC (Z).

提交回复
热议问题