#import <UIKit/UIKit.h>
@interface BYCountdownLabel : UILabel
/**根據目標時間計算跟服務器的差值*/
- (void)setupCountDownWithTargetTime:(NSDate *)targetTime;
@end
#import "BYCountdownLabel.h"
@interface BYCountdownLabel ()
/**時間定時器,用weak能夠在定時器銷燬以後指針自動置爲nil*/
@property (nonatomic, weak) NSTimer *timer;
/**天數*/
@property (nonatomic, assign) NSUInteger day;
/**小時數*/
@property (nonatomic, assign) NSUInteger hour;
/**分鐘數*/
@property (nonatomic, assign) NSUInteger minute;
/**秒數*/
@property (nonatomic, assign) NSUInteger second;
@end
@implementation BYCountdownLabel
- (void)setupCountDownWithTargetTime:(NSDate *)targetTime {
// 計算目標時間和當前服務器時間的時間差
NSTimeInterval interval = [targetTime timeIntervalSinceDate:[NSDate date]];
// 根據時間差的秒數計算天,小時,分鐘,秒(暫時不考慮月和年,月和年的倒計時用的不多)
[self calculateTime:(NSInteger)interval];
}
/**計算時間方法*/
- (void)calculateTime:(NSInteger)interval {
// 天
self.day = interval/86400; // 一天 == 86400 == 24*60*60秒
// 小時
self.hour = interval%86400/3600;
// 分鐘
self.minute = interval%3600/60;
// 秒
self.second = interval%60;
// 賦值到label上
self.text = [NSString stringWithFormat:@"%02zd天%02zd:%02zd:%02zd",
self.day, self.hour, self.minute, self.second];
// 一秒鐘後調用減一秒方法
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeDecrease) userInfo:nil repeats:YES];
}
/**時間減一秒方法*/
- (void)timeDecrease {
// 減一秒
self.second--;
// 判斷秒數
if (self.second == -1) {
self.second = 59;
// 分鐘減一
self.minute--;
}
// 判斷分鐘數
if (self.minute == -1) {
self.minute = 59;
// 小時減1
self.hour--;
}
// 判斷小時數
if (self.hour == -1) {
self.hour = 23;
// 天數減1
self.day--;
}
// 判斷是否沒時間了
if (self.day == 0 &&
self.hour == 0 &&
self.minute == 0 &&
self.second == 0) {
[self.timer invalidate];
}
// 賦值
self.text = [NSString stringWithFormat:@"%02zd天%02zd:%02zd:%02zd",
self.day, self.hour, self.minute, self.second];
}
@end
原文:http://bbs.520it.com/forum.php?mod=viewthread&tid=2591&pid=27758&page=1&extra=#pid27758
php