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

在公司写活动的时候,有个需求是对时间日期格式作转换。如  ' 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

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

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

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

    return month + day;
}
原文地址:https://www.cnblogs.com/intangible/p/9021097.html