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

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

    Drop-in solution

    const jsonDateRegexp = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d{3})Z$/;
    
    function jsonRetriever(key: string, value: any) {
      // let's try to detect input we dont have to parse early, so this function is as fast as possible
      if (typeof value !== 'string') {
        return value;
      }
    
      const dateMatch = jsonDateRegexp.exec(value);
    
      if (!dateMatch) {
        return value;
      }
    
      return new Date(
        Date.UTC(
          +dateMatch[1],
          +dateMatch[2] - 1,
          +dateMatch[3],
          +dateMatch[4],
          +dateMatch[5],
          +dateMatch[6],
          +dateMatch[7],
        ),
      );
    }
    
    export function parseJsonWithDates(input: string) {
      return JSON.parse(input, jsonRetriever);
    }
    

提交回复
热议问题