計(jì)算兩個(gè)時(shí)間戳之差,以及時(shí)間倒計(jì)時(shí)

項(xiàng)目中提交訂單之后,會(huì)有付款時(shí)間倒計(jì)時(shí)提醒,不過(guò)相關(guān)的接口中只提供了訂單提交時(shí)間戳,沒(méi)有訂單付款超時(shí)時(shí)間戳,后臺(tái)規(guī)定,訂單付款周期為24小時(shí),根據(jù)這個(gè)需求來(lái)進(jìn)行時(shí)間倒計(jì)時(shí)。

調(diào)用以下的方法得出當(dāng)前時(shí)間與超時(shí)時(shí)間的間距:

//time:周期時(shí)間 ? 單位為秒數(shù) ? ? ?timeStamp:訂單提交時(shí)間戳+ (NSTimeInterval)timerInterval:(NSTimeInterval)interval timeStamp:(NSString *)timeStamp{

//訂單下單時(shí)間

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

//訂單超時(shí)時(shí)間

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

//當(dāng)前時(shí)間

NSDate *nowDate = [NSDate date];

NSTimeInterval nowInterval = [nowDate timeIntervalSince1970];

NSTimeInterval endInterval = [endDate timeIntervalSince1970];

//得出當(dāng)前時(shí)間與超時(shí)時(shí)間的間距

NSTimeInterval value = endInterval - nowInterval;

return value;

}

再進(jìn)行時(shí)間的判斷,當(dāng)value > 0 時(shí),計(jì)時(shí)器啟動(dòng)倒計(jì)時(shí),小于等于0時(shí),訂單已超時(shí),計(jì)時(shí)器停止。

當(dāng)?value > 0時(shí),計(jì)時(shí)器啟動(dòng),調(diào)用以下方法:

+ (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;

}

計(jì)時(shí)器不斷給控件刷新數(shù)據(jù),NSTimer我就不贅述了,效果如下:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容