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

后端 未结 6 804
醉酒成梦
醉酒成梦 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:26

    Using TypeSript, my solution is as follows:

        export function parseWithDate(jsonString: string): any {
        var reDateDetect = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;  // startswith: 2015-04-29T22:06:55
        var resultObject = JSON.parse(jsonString,(key: any, value: any) => {
            if (typeof value == 'string' && (reDateDetect.exec(value))) {
                return new Date(value);
            }
            return value;
        });
        return resultObject;
    }
    

    Best of all worlds ;-) It uses an anonymous datereviver, which gets called by JSON.parse on each property. The reviver logic is to check whether the property is of type string and if so, whether it looks like the start of a date ... If it is a date, then let new Date(value) do the actual parsing ... all timezone variations are supported that way.

    Hope it helps!

提交回复
热议问题