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

最新一個(gè)活動(dòng)項(xiàng)目中,用到一個(gè)活動(dòng)開始倒計(jì)時(shí)時(shí)間。倒計(jì)時(shí)函數(shù)寫出來在chrome和安卓手機(jī)查看正常,但到了蘋果手機(jī)看就會(huì)顯示NaN,于是逐步調(diào)試,發(fā)現(xiàn)是初始化時(shí)間時(shí)發(fā)生的異常。如下

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

var startTime2 = new Date('2017-03-08T00:00:00');  //日期和時(shí)間中間加個(gè)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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容