在公司写活动的时候,有个需求是对时间日期格式作转换。如  ' 2018-05-01 00:00:00 ' 转换成 '5月1日'。

function formatTime (time) {
    var time = new Date(time),
          month = time.getMonth() + 1 + '',
         day = time.getDate() + '';

     return month + day;
}

在chrome浏览器可以正常显示,但是用ie8打开,出现问题了,页面中的日期显示为 NAN

javascript中new Date()的浏览器兼容性问题

 

最后查找出原因是:  基于'/'格式的日期字符串,才是被各个浏览器所广泛支持的,‘-’连接的日期字符串,则是只在chrome下可以正常工作。

故,我们要先将日期中的 '-' 替换为 '/' 就可以了。

formatTime = function (time) {
    var time = new Date(time.replace(/-/g,"/")),
          month = time.getMonth() + 1 + '',
          day = time.getDate() + '';

    return month + day;
}

 

相关文章:

  • 2022-12-23
  • 2021-12-24
  • 2021-05-27
  • 2021-12-02
猜你喜欢
  • 2022-01-02
  • 2022-12-23
  • 2021-06-28
  • 2021-05-20
  • 2021-08-24
相关资源
相似解决方案