最近在做微信小程序时候遇到这样一个坑,调取后端提供的接口,接收返回的时间格式是2020-03-18T01:57:23.000+0000,于是,我就开启了转换时间的踩坑之旅,当我按照正常的时间转换方式转换好的时间后,在后期测试时候发现安卓上正常显示,但是在苹果手机上显示NAN,于是我经过一番测试和折腾后找到了解决办法,现贴出解决代码共享给大家:

var timeFormat = function (timedata){
  var that = this
  var date = new Date(timedata.substr(0, 19));
  var Year = date.getFullYear();
  var Month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
  var d = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var Hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
  var Minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
  var Seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  var over_time = Year + "/" + Month + "/" + d + " " + Hours + ":" + Minutes + ":" + Seconds
 //***至此以上是将时间2020-03-18T01:57:23.000+0000转为正常时间格式,以下为将时间进行增加8小时解决时区差异的操作***
  var time = new Date(Date.parse(over_time));
  time.setTime(time.setHours(time.getHours() + 8));
  var Y = time.getFullYear() + '/';
  var M =addZero(time.getMonth() + 1) + '/';
  var D =addZero(time.getDate()) + ' ';
  var h = addZero(time.getHours()) + ':';
  var m =addZero(time.getMinutes()) + ':';
  var s =addZero(time.getSeconds());
  return (Y + M + D + " " + h + m + s) 
} 
//不足10 补0操作
var addZero=function (num) {
    return num < 10 ? '0' + num : num;
  }
module.exports = {
  addZero:addZero,
  timeFormat:timeFormat ,
}

 总结:1.需要将2020-03-18T01:57:23.000+0000进行.substr(0, 19)操作,否则容易转换失败,切记哦~

             2.时间转换完成后需要进行增加8小时的操作,是为了解决时区差异。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐