2013-01-08 56 views
1

我使用下面的代碼在Xcode:語法錯誤日期計算

(void)updateLabel 
{ 
    NSDate* now = [NSDate date]; 
    int hour = 23 - [[now dateWithCalendarFormat:nil timeZone:nil] hourOfDay]; 
    int min = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] minuteOfHour]; 
    int sec = 59 - [[now dateWithCalendarFormat:nil timeZone:nil] secondOfMinute]; 
    countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, min,sec]; 
} 

而且正在以下錯誤。我怎樣才能解決這個問題?

error: invalid operands to binary - (have 'int' and 'id')

+0

這行給出你的錯誤? –

+0

全部三個.......其中int用於小時,分鐘,秒 –

+0

我在我的系統中嘗試了相同的代碼,它工作良好。 –

回答

1

您必須使用這種方式: -

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[NSDate date]]; 
NSInteger hour = [dateComponents hour]; 
NSInteger minute = [dateComponents minute]; 
NSInteger second = [dateComponents second]; 
[gregorian release]; 

希望它可以幫助你

0

用這種方式

NSDate* now = [NSDate date]; 

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now]; 
long hour =23-[dateComponents hour]; 
long min =59-[dateComponents minute]; 
long sec =59-[dateComponents second]; 

NSString *str = [NSString stringWithFormat:@"%02ld:%02ld:%02ld", hour, min,sec]; 
NSLog(@"--> %@",str);