计算两个时间戳之差,以及时间倒计时

项目中提交订单之后,会有付款时间倒计时提醒,不过相关的接口中只提供了订单提交时间戳,没有订单付款超时时间戳,后台规定,订单付款周期为24小时,根据这个需求来进行时间倒计时。

调用以下的方法得出当前时间与超时时间的间距:

//time:周期时间   单位为秒数      timeStamp:订单提交时间戳+ (NSTimeInterval)timerInterval:(NSTimeInterval)interval timeStamp:(NSString *)timeStamp{

//订单下单时间

NSDate *beginDate = [NSDate dateWithTimeIntervalSince1970:[timeStamp intValue]];

//订单超时时间

NSDate *endDate = [NSDate dateWithTimeInterval:interval sinceDate:beginDate];

//当前时间

NSDate *nowDate = [NSDate date];

NSTimeInterval nowInterval = [nowDate timeIntervalSince1970];

NSTimeInterval endInterval = [endDate timeIntervalSince1970];

//得出当前时间与超时时间的间距

NSTimeInterval value = endInterval - nowInterval;

return value;

}

再进行时间的判断,当value > 0 时,计时器启动倒计时,小于等于0时,订单已超时,计时器停止。

当 value > 0时,计时器启动,调用以下方法:

+ (NSString *)countdownTime:(NSTimeInterval)interval{

NSString *timeStr;

int second = (int)interval % 60;//秒

int minute = (int)interval / 60 % 60;

int hours = (int)interval / 3600 % 60;

int day = (int)interval / (24 *3600) % 60;

if (day != 0) {

timeStr = [NSString stringWithFormat:@"%d天%d:%d:%d",day,hours,minute,second];

}else if (day == 0 && hours != 0) {

timeStr = [NSString stringWithFormat:@"%d:%d:%d",hours,minute,second];

}else if (day == 0 && hours == 0 && minute != 0) {

timeStr = [NSString stringWithFormat:@"%d:%d",minute,second];

}else{

timeStr = [NSString stringWithFormat:@"%d",second];

}

return timeStr;

}

计时器不断给控件刷新数据,NSTimer我就不赘述了,效果如下:

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容