//定时器
m_pTimer= [NSTimerscheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(calcuRemainTime)
userInfo:nil
repeats:YES];
//开始时间获取
m_pStartDate=[NSDatedate];
// m_pStartDate = [[NSDatedate] retain];
==============
#define TOTAL_TIME3600
- (void)calcuRemainTime
{
doubledeltaTime =[[NSDatedate]timeIntervalSinceDate:m_pStartDate];
// NSLog(@"%.f",deltaTime);
// NSLog(@"%d",(int)(deltaTime+0.5));
intremainTime=TOTAL_TIME-(int)(deltaTime+0.5) ;
if(remainTime<0.0)
{
[m_pTimerinvalidate];
//TODO:
//game over
return;
}
[selfshowTime:remainTime];
}
- (void)showTime:(int)time
{
intinputSeconds= (int)time;
inthours= inputSeconds /3600;
intminutes = (inputSeconds - hours *3600)/60;
intseconds =inputSeconds - hours *3600- minutes*60;
NSString*strTime= [NSStringstringWithFormat:@"%.2d:%.2d:%.2d",hours,minutes,seconds];
//显示在文本视图中
NSLog(@"==%@",strTime);
}
第二种方式:
[NSTimerscheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(timerFireMethod:) userInfo:nilrepeats:YES];//使用timer定时,每秒触发一次,然后就是写selector了。
-(void)timerFireMethod:(NSTimer*)theTimer{
//NSDateFormatter*dateformatter = [[[NSDateFormatter alloc]init]autorelease];//定义NSDateFormatter用来显示格式
//[dateformattersetDateFormat:@"yyyy MM dd hh mm ss"];//设定格式
NSCalendar *cal = [NSCalendarcurrentCalendar];//定义一个NSCalendar对象
NSDateComponents *shibo = [[NSDateComponentsalloc] init];//初始化目标时间(好像是世博会的日期)
[shibo setYear:2010];
[shibo setMonth:5];
[shibo setDay:1];使用NSTimer实现倒计时
[shibo setHour:8];
[shibo setMinute:0];
[shibo setSecond:0];
NSDate *todate = [caldateFromComponents:shibo];//把目标时间装载入date
[shibo release];
// NSString *ssss = [dateformatter stringFromDate:dd];
// NSLog([NSString stringWithFormat:@"shiboshi:%@",ssss]);
NSDate *today = [NSDate date];//得到当前时间
// NSString *sss = [dateformatter stringFromDate:today];
// NSLog([NSString stringWithFormat:@"xianzaishi:%@",sss]);
//用来得到具体的时差
unsigned int unitFlags = NSYearCalendarUnit |NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *d = [cal components:unitFlagsfromDate:today toDate:todate options:0];
lab.text = [NSStringstringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day],[d hour], [d minute], [d second]];
}