思路:让后台传一个抢购截止的时间,然后你写一个方法与当前时间做比较,将相差的时间显示出来
//定时器
@property(nonatomic,strong)NSTimer *timedSpecialtimer;
self.timedSpecialtimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeTime) userInfo:nil repeats:YES];
#pragma mark -
#pragma mark 定时器
-(void)changeTime
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时区 GMT
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// 加入一些别的英文字符串时,需用单引号来引入
[formatter setDateFormat:@"yyyy年MM月dd日 HH点mm分ss秒 'iOS Date Test'"];
// NSString 转 NSDate
NSDate *date = [formatter dateFromString:@"2017年06月23日 11点46分00秒"];
self.remainingTimeStr = [self remainingTimeMethodAction:date];
[self.timedSpecialTableView reloadData];
}
方法:
/**
* 倒计时
*
* @param endTime 截止的时间戳
*
* @return 返回的剩余时间
*/
- (NSString*)remainingTimeMethodAction:(NSDate *)endTime
{
//得到当前时间
NSDate *date = [NSDate date]; // 获得时间对象
NSTimeZone *zone = [NSTimeZone systemTimeZone]; // 获得系统的时区
NSTimeInterval time = [zone secondsFromGMTForDate:date];// 以秒为单位返回当前时间与系统格林尼治时间的差
NSDate *nowData = [date dateByAddingTimeInterval:time];// 然后把差的时间加上,就是当前系统准确的时间
NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSCalendarIdentifierGregorian ];
NSUInteger unitFlags =
NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;
NSDateComponents *cps = [chineseClendar components:unitFlags fromDate:nowData toDate: endTime options:0];
NSInteger Hour = [cps hour];
NSInteger Min = [cps minute];
NSInteger Sec = [cps second];
NSInteger Day = [cps day];
// NSInteger Mon = [cps month];
// NSInteger Year = [cps year];
NSString *countdown = [NSString stringWithFormat:@"还剩: %zi天 %zi小时 %zi分钟 %zi秒 ", Day,Hour, Min, Sec];
if (Sec<0) {
countdown=[NSString stringWithFormat:@"活动结束/开始抢购"];
[self.timedSpecialtimer invalidate];
}
NSLog(@"countdown = %@",countdown);
return countdown;
}