实现类似促销商品或活动倒计时功能,当前时间距某个指定时间还剩:12:06:43(时:分:秒) 。
1、创建定时器(可以使用GCD定时器,也可以使用NSTimer,本文使用NSTimer)
NSTimer *countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
self.countDownTimer = countDownTimer;
[[NSRunLoop mainRunLoop] addTimer:countDownTimer forMode:NSRunLoopCommonModes];
2、实现定时调用的方法
pragma mark 倒计时时间
-(void)countDownAction{
// getTomorrowDay 为自定义NSDate分类方法:实现获取明天凌晨整点时间
NSString *tomorrowStr = [NSDate getTomorrowDay:[NSDate date]];
// compareNowDateToEndDateForSecound :实现当前时间距离指定时间间隔秒数
int timeout = [Common compareNowDateToEndDateForSecound:tomorrowStr].intValue;
// 计算时分秒
int days = (int)(timeout/(3600*24));
int hours = (int)((timeout-days*24*3600)/3600);
int minute = (int)(timeout-days*24*3600-hours*3600)/60;
int second = timeout-days*24*3600-hours*3600-minute*60;
// 更新UI显示
if (hours<10) {
self.hourLabel.text = [NSString stringWithFormat:@"0%d",hours];
}else{
self.hourLabel.text = [NSString stringWithFormat:@"%d",hours];
}
if (minute<10) {
self.minuteLabel.text = [NSString stringWithFormat:@"0%d",minute];
}else{
self.minuteLabel.text = [NSString stringWithFormat:@"%d",minute];
}
if (second<10) {
self.secondLabel.text = [NSString stringWithFormat:@"0%d",second];
}else{
self.secondLabel.text = [NSString stringWithFormat:@"%d",second];
}
}
3、传入今天的时间,返回明天的时间(整点时间)
+ (NSString *)getTomorrowDay:(NSDate *)aDate {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
[components setDay:([components day]+1)];
NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
[dateday setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
return [dateday stringFromDate:beginningOfWeek];
}
4、比较当前日期和指定日期的时间间隔秒数
+(NSString *)compareNowDateToEndDateForSecound:(NSString *)endDate{
NSString * nowDateStr =[Common dateToString:[NSDate date] format:@"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate =[Common dateFromString:nowDateStr format:@"yyyy-MM-dd HH:mm:ss"];
NSDate *toDate =[Common dateFromString:endDate format:@"yyyy-MM-dd HH:mm:ss"];
//利用NSCalendar比较日期的差异
NSCalendar *calendar = [NSCalendar currentCalendar];
//比较的结果是NSDateComponents类对象
NSDateComponents *delta = [calendar components:NSCalendarUnitSecond fromDate:startDate toDate:toDate options:0];
return [NSString stringWithFormat:@"%ld",delta.second] ;
}
方法中用到的Common类是自定义的工具类,dateToString和dateFromString为自定义工具类的方法,实现日期格式转换格式化功能,比较简单,在此就不贴出了,本文实现的倒计时功能中用到的方法只是自己想到的实现方式,如果有哪位朋友有更便捷的实现方式可以留言给我,很乐意向大家学习