项目中要实现如图的效果
1.定时器每秒刷新
- (void)awakeFromNib {
[super awakeFromNib];
self.timeLabel.backgroundColor = [UIColor colorWithWhite:1 alpha:0.7];
self.timeLabel.layer.masksToBounds = YES;
self.timeLabel.layer.cornerRadius = 5.0f;
self.timeLabel.textColor = [UIColor darkGrayColor];
self.timeLabel.font = [UIFont systemFontOfSize:14];
_timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownAction) userInfo:nil repeats:YES];
}
2.后台获取活动的开始时间和结束时间,调用封装好的方法
-(void)countDownAction
{
//活动开始时间
NSString *startStr = [tools timeWithTimeIntervalString:self.purchaseModel.startTime];
//活动结束时间
NSString *endStr = [tools timeWithTimeIntervalString:self.purchaseModel.endTime];
//显示
NSString *chaString= [tools dateTimeDifferenceWithStartTime:startStr endTime:endStr];
self.timeLabel.text = [NSString stringWithFormat:@"%@",chaString];
}
方法是比较三个时间,当前时间,开始时间和结束时间
+ (NSString *)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime
{
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *nowD = [NSDate date];
NSDate *endD = [date dateFromString:endTime];
NSDate *startD = [date dateFromString:startTime];
NSTimeInterval now = [nowD timeIntervalSince1970]*1;
NSTimeInterval end = [endD timeIntervalSince1970]*1;
NSTimeInterval start = [startD timeIntervalSince1970]*1;
//now是现在时间 end是结束的时间
if ((end -now>0)&&( now - start>0)){
//if (end >now>start) {
NSTimeInterval value = end - now;
int second = (int)value %60;//秒
int minute = (int)value /60%60;
int house = (int)value / (24 *3600)%3600;
int day = (int)value / (24 *3600);
NSString *str;
if (day != 0) {
str = [NSString stringWithFormat:@"距结束%d天%d小时%d分%d秒",day,house,minute,second];
}else if (day==0 && house !=0) {
str = [NSString stringWithFormat:@"距结束%d小时%d分%d秒",house,minute,second];
}else if (day==0 && house==0 && minute!=0) {
str = [NSString stringWithFormat:@"距结束%d分%d秒",minute,second];
}else{
str = [NSString stringWithFormat:@"距结束%d秒",second];
}
return str;
}else if (now -start<0)
{
NSTimeInterval value = start-now;
int second = (int)value %60;//秒
int minute = (int)value /60%60;
int house = (int)value / (24 *3600)%3600;
int day = (int)value / (24 *3600);
NSString *str;
if (day != 0) {
str = [NSString stringWithFormat:@"距开始%d天%d小时%d分%d秒",day,house,minute,second];
}else if (day==0 && house !=0) {
str = [NSString stringWithFormat:@"距开始%d小时%d分%d秒",house,minute,second];
}else if (day==0 && house==0 && minute!=0) {
str = [NSString stringWithFormat:@"距开始%d分%d秒",minute,second];
}else{
str = [NSString stringWithFormat:@"距开始%d秒",second];
}
return str;
}else
{
NSString *str = @" 已结束 ";
return str;
}
}
网友评论