React.jpeg
購物項目一般有的商品會有限時搶購商品,限時搶購又根據當前時間來算有兩個狀態:1.預售(當前時間到開售時間之間的狀態) 2.在售(當前時間到搶購結束時間之間的狀態)。
下面來介紹下之間的換算邏輯:
1.獲取當前時間戳
// 獲取當前時間戳
const currentTimestamp = new Date().getTime();
2.服務器返回的時間戳
// 獲取某個時間格式的時間戳
const otherTime = 服務端返回的時間;
/* eslint-disable */
const newstr = otherTime(/-/g,'/');
/* eslint-enable */
const date = new Date(newstr);
const otherTimestamp = date.getTime().toString();
3.計算兩者差值,獲取時間段
//在售(當前時間到搶購結束時間之間的狀態)
if (parseFloat(currentTimestamp) >= parseFloat(otherTimestamp)) {
date3 = otherTimestamp - currentTimestamp;
// console.log('在售獲得差值:'+ date3);
}
//預售(當前時間到開售時間之間的狀態)
else if (parseFloat(currentTimestamp) < parseFloat(otherTimestamp)) {
date3 = otherTimestamp - currentTimestamp;
// console.log('預售獲得差值:'+ date3);
}
4.根據獲取的時間戳計算出天時分秒
// 天
const days = Math.floor(date3 / (24 * 3600 * 1000));
// 時
const leave1 = date3 % (24 * 3600 * 1000);
const hours = Math.floor(leave1 / (3600 * 1000));
// 分
const leave2 = leave1 % (3600 * 1000);
const minutes = Math.floor(leave2 / (60 * 1000));
// 秒
const leave3 = leave2 % (60 * 1000);
const seconds = Math.round(leave3 / 1000);
// console.log("天:"+days+",時:"+hours+",分:"+minutes+",秒:"+seconds);