用NSTimer实现倒计时--ios开发

本文介绍如何使用Objective-C中的NSTimer实现倒计时功能,并详细展示了通过NSDate及NSCalendar进行日期时间计算的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先定义NSTimer

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];

倒计时在timer的触发方法里完成

- (void)timerFireMethod:(NSTimer *)timer

{

    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [[NSDateComponents allocinit];

    [components setYear:2012];

    [components setMonth:8];

    [components setDay:13];

    [components setHour:12];

    [components setMinute:0];

    [components setSecond:0];

    NSDate *fireDate = [calendar dateFromComponents:components];//目标时间

    NSDate *today = [NSDate date];//当前时间

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit;

     NSDateComponents *d = [calendar components:unitFlags fromDate:today toDate:fireDate options:0];//计算时间差

    auctionTime.text = [NSString stringWithFormat:@"%d%d小时%d%%d", [d day], [d hour], [d minute], [d second]];//倒计时显示

}

这样就完成了倒计时。

不过如果有专门的服务器时,要把服务器和自己本机的时间差考虑进去


转载:http://blog.csdn.net/sapphire_aling/article/details/7858859



NSDate时间计算(计算某个时间之前或之后的某个时间)


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];

    [formatter setDateFormat:(@"yyyy-MM-dd HH:mm:ss")];

    NSDate *date = [formatter dateFromString:@"2012-08-08 08:08:08"];//既定时间,下面计算它半个小时以前的时间和半小时以后的时间

    NSDate *before = [date dateByAddingTimeInterval:-30*60];

    NSDate *after = [date dateByAddingTimeInterval:30*60];

转载:http://blog.csdn.net/sapphire_aling/article/details/7900345
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值