android 时间差 秒_计算时间差,页面倒计时,安卓与ios兼容问题

前言

在开发一些有关商品交易类的项目时,多半会遇到活动倒计时之类的需求,最近也是在小程序中遇到,实现方法很多,但是在小程序中遇到ios和安卓的兼容问题,所以记录下来

代码

/**

* timestampSwitch - 根据对比传入的两个时间戳,计算出相差的时分秒

*

* @param{String}startTimestamp 计算起始时间戳,默认是当前时间

* @param{Number}endTimestamp 计算结束时间(当前接受的是时间字符串,如2018-11-30 23:59:59)

* @return{Object}

*/

const timestampSwitch = (endTimestamp, startTimestamp = (new Date()).valueOf()) => {

if (!Number(endTimestamp) || !Number(startTimestamp)) console.error('Incorrect parameter');

// 兼容ios

let et = Date.parse(endTimestamp) || Date.parse(endTimestamp.replace(/-/g, '/'));

// 计算

let difference = (endTimestamp - startTimestamp),

timeDifference = (difference > 0 ? difference : 0) / 1000,

days = parseInt(timeDifference / 86400),

hours = parseInt((timeDifference % 86400) / 3600),

minutes = parseInt((timeDifference % 3600) / 60),

seconds = parseInt(timeDifference % 60);

return {

days,

hours,

minutes,

seconds

}

};

问题

问题在于后台给我的是时间字符串,我们需要转为时间戳后计算,但是安卓和ios转换时会有不同如上代码

iOS中Date.parse(endTimestamp)转为时间戳会报错,兼容性方法Date.parse(endTimestamp.replace(/-/g, '/'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值