2012-07-18 39 views
-2

我想要倒计时,显示日,小时,M和S.第二次被调用一次。如何在objc中比较时间

- (void)changetime {  

    NSCalendar *cal = [NSCalendar currentCalendar];//定义一个NSCalendar对象     
    NSDate *today = [NSDate date];//得到当前时间 

    unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
    NSDateComponents *weekdayComponents =[cal components:(unitFlags) fromDate:self.overDate]; 
    NSDate *todate = [cal dateFromComponents:weekdayComponents]; 
    NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:todate options:0]; 

    NSInteger days=[d year]*365+[d month]*31+[d day]; 
    if ([self.overDate earlierDate:[NSDate date]]==self.overDate) { 
     [myTimer invalidate]; 
     myTimer=nil; 
     self.labdate.text = [NSString stringWithFormat:@"%d天%d时%d分%d秒",days, [d hour], [d minute], [d second]]; 
     return; 
    }  
    self.labdate.text = [NSString stringWithFormat:@"%d天%d时%d分%d秒",days, [d hour], [d minute], [d second]];  
} 

myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changetime) userInfo:nil repeats:YES]; 

self.overDate=[wedding date];//this is a future time 

回答

2

下面一行应引起你报警:

NSInteger days=[d year]*365+[d month]*31+[d day]; 

有一年仅365天〜在公历75%的时间。近50%的月份在该日历中没有31天。请查看苹果文档中的Date Calculations部分,该部分告诉您如果您要求提供日组件,并且您的components:fromDate:toDate:options:调用中没有更大的组件,那么您将获得需要考虑日历的天数。