最近发现new Date()格式化在Chrome显示正常,但是在Safari中就有问题,在网上搜集资料,发现有三种解决办法,整理如下:
第一,用正则表达式做简单的匹配有两种方式:
1. 如果只有个别JS文件,建议采用这种方式
new Date('2017-03-12'.replace(/-/g, "/")).format("yyyy-MM-dd hh:mm");
2. 提取一个共同的方法
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[0], parts[1]-1, parts[2]);
}
parseDate('2011-01-03'); // Mon Jan 03 2011 00:00:00
参照如下:new Date() using Javascript in Safari
10
3
|
I’m having an issue using the new Date() function in Javascript. Safari is giving me an “Invalid Date” message. I’ve created a short example at jsbin. This appears to work on all other browsers, but not Safari. Any ideas on how I can take the value from an input (such as 2011-01-03) and turn it into a date object, while having it work properly in Safari? Many thanks! |
|||
add a comment
|
||||
36 |
The date parsing behavior on JavaScript is implementation-dependent, the ISO8601 format was recently added to the ECMAScript 5th Edition Specification, but this is not yet supported by all implementations. I would recommend you to parse it manually, for example:
Basically the above function matches each date part and uses the Date constructor, to build a date object, note that the months argument needs to be 0-based (0=Jan, 1=Feb,…11=Dec). |
||
第二,引入DateJS格式化标准日期库 参考:DateJS
var currentDate = Date.parseExact("2017-01-12", "dd-MM-yyyy");
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/164235.html
Dodinas
Jan 7 ’11 at 8:01