Safari中new Date()格式化问题总结

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。Safari中new Date()格式化问题总结,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

最近发现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

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!

share

edit

flag
 
 

4 Answers

up vote
36
down vote
accepted

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:

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

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).

share

edit

flag
 
 
This did it. Thanks for the clarification. – 
Dodinas 
Jan 7 ’11 at 8:01

第二,引入DateJS格式化标准日期库   参考:DateJS

var currentDate = Date.parseExact("2017-01-12", "dd-MM-yyyy");

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/164235.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!