美文网首页
微信ios/Safari中的new Date()格式化坑

微信ios/Safari中的new Date()格式化坑

作者: 独享奢华 | 来源:发表于2017-03-08 16:39 被阅读4610次

最新一个活动项目中,用到一个活动开始倒计时时间。倒计时函数写出来在chrome和安卓手机查看正常,但到了苹果手机看就会显示NaN,于是逐步调试,发现是初始化时间时发生的异常。如下

var startTime = new Date('2017-03-08 00:00:00');   //ios中starTime为NaN

var startTime2 = new Date('2017-03-08T00:00:00');  //日期和时间中间加个T,兼容ios


以下是原文:
I suggest you use:

new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

To split the string you could try

var s = '2017-03-08T14:27:28.593Z';
var a = s.split(/[^0-9]/);
//for (i=0;i<a.length;i++) { alert(a[i]); }
var d=new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
alert(s+ " "+d);

To make your question easier your problem is with:

new Date('2014-02-18 15:00:48')

This work okay in chrome but not in safari. The mdn talks about ECMAScript 5 ISO-8601 format support says:

Alternatively, the date/time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.

If you include T
it works:

new Date('2014-02-18T15:00:48')

You can use

new Date('2014-02-18T15:00:48'.replace(/\s/, 'T'))

If you handle a lot of cases like this I will recommend using moment which seems to handle this case very well with or without T: parsing from string. Additionally your whole example is easier with momentjs:

var minutes = moment().diff("2014-02-18 15:00:48", 'minutes');

原文链接:http://blog.csdn.net/pkueecser/article/details/53140999

相关文章

网友评论

      本文标题:微信ios/Safari中的new Date()格式化坑

      本文链接:https://www.haomeiwen.com/subject/tgdbgttx.html