美文网首页
iOS格式化时间NaN问题

iOS格式化时间NaN问题

作者: Yinzhishan | 来源:发表于2018-12-06 23:50 被阅读0次
问题

我们再做移动端页面时经常会遇到需要格式化时间的问题,但是有时安卓端和iOS对时间的表现却不一样,在iOS端有时会出现NaN的现象,而安卓端却没有问题。

表现

我们先写一个格式化代码的方法:

//格式化时间
  var formattingDate =  function(timedata) {
      var date = new Date(timedata);
      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();
      return (Year + "-" + Month + "-" + d + " " + Hours + ":" + Minutes + ":" + Seconds);
  }

然后我们分别在chromeSafari中运行,传入相同的入参,观察返回值:

chrome.png Safari.png

由上图可见当我们的格式化方法的入参是使用-来链接时,就有可能会出现两端表现不一致的现象。

解决方法

我们可以使用正则表达式将入参的连接方式替换/,来对我们的格式化方法进行强化:

//格式化时间
  var formattingDate =  function(timedata) {
      var date = new Date(timedata.replace(/-/g, '/'));
      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();
      return (Year + "-" + Month + "-" + d + " " + Hours + ":" + Minutes + ":" + Seconds);
  }

这样,我们的方法就不会出现两端格式化不一致的情况了。

欢迎大家关注、分享、点赞哦!

相关文章

网友评论

      本文标题:iOS格式化时间NaN问题

      本文链接:https://www.haomeiwen.com/subject/ijhicqtx.html