React Native之计算服务器获取时间戳与当前时间的差值(算出天时分秒)

React Native之计算服务器获取时间戳与当前时间的差值(算出天时分秒)_第1张图片
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);
到这里就能获取到展示的时间天时分秒了,得到的时间可以给倒计时控件使用。

大家有什么不懂得可以留言,看见第一时间回复。

你可能感兴趣的:(React Native之计算服务器获取时间戳与当前时间的差值(算出天时分秒))