倒计时定时器

这里写图片描述
项目要求 根据后台返回的时间戳 进行商品拍卖定时倒计时
后台返回的时间格式是:yyyy-MM-dd HH:mm:ss
写了一个时间转换工具将后台返回的时间字符串转换为指定的时间格式如下:

+ (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 类型的时间值
将这个时间值转化为固定样式的时间格式 代码如下:

+ (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;
}

实现定时器 创建定时器

- (NSTimer *)auctionTimer {
    if (!_auctionTimer) {
        _auctionTimer = [CZTimerTool scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(auctionTimerAction) userInfo:nil repeats:YES];
    }
    return _auctionTimer;
}

通过时间的截取 实现定时器显示效果

-(void)auctionTimerAction
{
    self.timeInterval -= 1;
    NSString *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)];
}

这样就实现了上图的定时器效果。

发布了46 篇原创文章 · 获赞 1 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章