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

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

    1. The regular expression expects a "Zulu" timezone (A 'Z' character at the end), while the sample date-time string shows a numeric timezone ('-04:00'). The following regex will accept both:

      /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)(Z|([+\-])(\d{2}):(\d{2}))$/
      

      If the time zone digits are not zero, you might want to actually modify the date after parsing and/or converting to UTC, to respect the timezone.

    2. I can see dateReviver() being hit. Try the following in a browser:

      
      
          
              
              
              
          
          
              

      I am getting the following in the browser, indicating successful parsing:

      Sat Apr 4 15:55:16 PDT 2009
      

提交回复
热议问题