苹果浏览器 时间格式 兼容问题的坑 最后给一个非常完美的字符串转Date对象的函数

很多人知道如下写法来兼容苹果浏览器,但是其实这个写法也是有问题的

  function praseTime(time){
 let date = new Date(time.replace(/-/g,'/'))
 return date;
 };

因为 像这样的时间格式 2009-12-28T00:00:00.000+00:00 用/替换-后,是无法再转换为Date的。
如图

最后还有一个坑 date == 'Invalid Date'是不全面的,有时候date会NaN;我现在无法重现了。但是调试代码中的确遇到过这个辛苦

   date = new Date(time)
  if (date == 'Invalid Date') return time;// date == 'Invalid Date'是不全面的,有时候date会NaN

最后给一个非常完美的字符串转Date对象的函数

      //字符串转Date
      function parseDate(time) {
        if (!time) {
          return {};
        }

           if (time instanceof Date) {
           return time;
          }

             if (typeof time !== "string") {
               return {};
              }

              let date = new Date(time);
                if (date.getDay() === "NaN") {
                /**考虑是苹果浏览器不兼容的情况 */
                 date = new Date(time.replace(/-/g, "/"));
                   /**还是NaN 考虑是不合法的时间字符串 */
                           if (date.getDay() === "NaN") {
                   return {};
              }
                  }

               return date;
              }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章