小程序在iOS端,时间显示NaN的根本原因

现象:在微信开发工具测试时间显示正常、真机测试时间显示正常。安卓手机测试时间显示正常、开发工具连接iOS手机测试时间显示正常。

体验版中,iOS手机测试时间显示NaN。

原因:当进行网络请求的时候,后端返回日期格式:“2018-05-03”。iOS手机或者浏览器不支持这种类型的日期格式。
例如:

      console.log("2019-10-09 19:42:46")
      console.log(Date.parse("2019-10-09 19:42:46"))
      console.log(Date.parse("2019-10-09 19:42:46".replace(/-/g,'/')))

ios浏览器转化为时间戳效果如图:
在这里插入图片描述

需要转换日期格式:

   const  time = "2018-05-03"
   time.replace(/\-/g, "/");
   console.log(time);         2019/05/03
   
   
  // 在小程序的工具文件util.js中进行封装
  function formatTime(date) {
      var time = date==null?"": Date.parse(date.replace(/-/g, '/'));
      var date = new Date(time);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      var hour = date.getHours();
      var minute = date.getMinutes();
      var second = date.getSeconds();
      return [year, month, day].map(formatNumber).join('/');
    }

这里为什么将日期转化为时间戳?

因为后端返回的只有日期,如果直接将日期转换为格式:“2019/05/03”,在iOS端时间还是显示NaN。

发布了102 篇原创文章 · 获赞 26 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/xuelian3015/article/details/102486965