背景
最近一個項目要做一個倒計時功能(如下圖),自然首要的是想到用結束時間時間戳 - 當前手機時間時間戳
,然后由得到的差值計算還剩 N天N小時N分N秒
image.png
var nowTimestamp = new Date().getTime();
var endTimestamp = new Date("2018-07-26 14:58:32").getTime();
var leftSeconds = endTimestamp - nowTimestamp;
console.log("當前時間時間戳",nowTimestamp);
console.log("結束時間時間戳",endTimestamp);
console.log("差值",leftSeconds);
PC端輸出
問題描述 : PC端調試頁面,發現一切是那么的順利,計算出了準確的時間戳。可是(OK,there is always a but );是的當我把這個頁面,在手機端查看時,發現安卓正常,但是 ios呢卻是NaN
ios時間戳獲取演示
原因
原來當我獲取結束時間時間戳時,new Date("2018-07-26 14:58:32"); 返回 Invalid Date
(錯誤的時間格式),用錯誤的時間對象再去獲取時間戳,自然是 NaN
, ios 下的 new Date() 只能識別 2018/07/26 14:58:32
格式的字符串來生成日期對象。
解決
既然ios下的new Date() 只能識別 2018/07/26 14:58:32
格式的,那么我們只需要把我們原格式中的 -
替換為 /
即可,即
var nowTimestamp = new Date().getTime();
var endTimestamp = new Date("2018-07-26 14:58:32".replace(/-/g,"/")).getTime();
var leftSeconds = endTimestamp - nowTimestamp;
console.log("當前時間時間戳",nowTimestamp);
console.log("結束時間時間戳",endTimestamp);
console.log("差值",leftSeconds);