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

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Web3&Basketball

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值