2012-07-18 38 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:調用中沒有更大的組件,那麼您將獲得需要考慮日曆的天數。