生活随笔
收集整理的這篇文章主要介紹了
倒计时定时器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
項目要求 根據(jù)后臺返回的時間戳 進(jìn)行商品拍賣定時倒計時
后臺返回的時間格式是:yyyy-MM-dd HH:mm:ss
寫了一個時間轉(zhuǎn)換工具將后臺返回的時間字符串轉(zhuǎn)換為指定的時間格式如下:
+ (
NSTimeInterval)timeIntervalSinceNowWithDateStr:(
NSString *)dateStr {NSDateFormatter *formatter = [[NSDateFormatter alloc] init];formatter
.dateFormat = @
"yyyy-MM-dd HH:mm:ss";
NSDate *date = [formatter dateFromString:dateStr];
return [date timeIntervalSinceNow];
}
返回得到的是一個NSTimeInterval 類型的時間值
將這個時間值轉(zhuǎn)化為固定樣式的時間格式 代碼如下:
+ (
NSString *)intervalTimeStrWithTimeInterval:(
NSTimeInterval)timeInterval {
if (timeInterval <
0) {
return @
"00:00:00";}
int interval = timeInterval;
NSString *intervalStr = @
"";
NSString *hh = [
NSString stringWithFormat:@
"%d",interval/
3600];
if ([hh length] ==
1){hh = [
NSString stringWithFormat:@
"0%@",hh];}
NSString *mm = [
NSString stringWithFormat:@
"%d",(interval/
60)%
60];
if ([mm length] ==
1){mm = [
NSString stringWithFormat:@
"0%@",mm];}
NSString *ss = [
NSString stringWithFormat:@
"%d",interval%
60];
if ([ss length] ==
1){ss = [
NSString stringWithFormat:@
"0%@",ss];}intervalStr = [
NSString stringWithFormat:@
"%@:%@:%@",hh,mm,ss];
return intervalStr;
}
實現(xiàn)定時器 創(chuàng)建定時器
- (NSTimer *)auctionTimer {
if (!_auctionTimer) {_auctionTimer = [CZTimerTool scheduledTimerWithTimeInterval:
1.0f target:
self selector:
@selector(auctionTimerAction) userInfo:
nil repeats:
YES];}
return _auctionTimer;
}
通過時間的截取 實現(xiàn)定時器顯示效果
-(void)auctionTimerAction
{self
.timeInterval -=
1NSString *timeText = [CZDateTool intervalTimeStrWithTimeInterval:self
.timeInterval]self
.hourLabel.text = [timeText substringWithRange:NSMakeRange(
0,
2)]self
.minuteLabel.text = [timeText substringWithRange:NSMakeRange(
3,
2)]self
.secondLabel.text = [timeText substringWithRange:NSMakeRange(
6,
2)]
}
這樣就實現(xiàn)了上圖的定時器效果。
總結(jié)
以上是生活随笔為你收集整理的倒计时定时器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。