今天在CocoaChina上面看到有人在問倒計(jì)時(shí)怎么做,記得以前在看Iphone31天的時(shí)候做過一個(gè),今天翻出來運(yùn)行不了了,原因是我的Iphone SDK升級(jí)到3.1了,以前使用的是2.2.1,在2.2.1里面是可以使用NSCalendarDate的,但是在3.1里面不能夠使用,怎么辦,只好用NSTimer了,最后還是給實(shí)現(xiàn)了。代碼也比較簡(jiǎn)單,開始運(yùn)行viewDidLoad的時(shí)候加載 [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];//使用timer定時(shí),每秒觸發(fā)一次,然后就是寫selector了。
- (void)timerFireMethod:(NSTimer*)theTimer
{
//NSDateFormatter *dateformatter = [[[NSDateFormatter alloc]init] autorelease];//定義NSDateFormatter用來顯示格式
//[dateformatter setDateFormat:@"yyyy MM dd hh mm ss"];//設(shè)定格式
NSCalendar *cal = [NSCalendar currentCalendar];//定義一個(gè)NSCalendar對(duì)象
NSDateComponents *shibo = [[NSDateComponents alloc] init];//初始化目標(biāo)時(shí)間(好像是世博會(huì)的日期)
[shibo setYear:2010];
[shibo setMonth:5];
[shibo setDay:1];使用NSTimer實(shí)現(xiàn)倒計(jì)時(shí)
[shibo setHour:8];
[shibo setMinute:0];
[shibo setSecond:0];
NSDate *todate = [cal dateFromComponents:shibo];//把目標(biāo)時(shí)間裝載入date
[shibo release];
// NSString *ssss = [dateformatter stringFromDate:dd];
// NSLog([NSString stringWithFormat:@"shibo shi:%@",ssss]);
NSDate *today = [NSDate date];//得到當(dāng)前時(shí)間
// NSString *sss = [dateformatter stringFromDate:today];
// NSLog([NSString stringWithFormat:@"xianzai shi:%@",sss]);
//用來得到具體的時(shí)差
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0];
lab.text = [NSString stringWithFormat:@"%d年%d月%d日%d時(shí)%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]];
}
這樣就實(shí)現(xiàn)了倒計(jì)時(shí)的功能。
原文:http://blog.sina.com.cn/s/blog_60b45f230100f3v2.html