2011-06-15 46 views
0

我想比較當前時間10:15的時間,然後找到差異即。時間爲10點15分。一切編譯,但我總是得到75 ....有人可以幫忙嗎?如果可能,我會非常喜歡編碼示例。此外,我試圖使用 - (時間間隔)timeIntervalSinceNow,但我無法弄清楚如何工作,所以如果任何人也有這樣的解釋,我會非常感謝 *注意我使用的是版本3.2.6,請指教因此,謝謝如何正確找到此代碼中的時差?

NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] 
            initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = 
[gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today]; 

NSInteger hour = [components hour]; 
NSInteger minute = [components minute]; 
NSInteger second = [components second]; 


NSInteger combo = hour + (minute/60) + (second/3600); 

NSTimeInterval time = combo*60*60; 

NSTimeInterval tenFifteenFirstPeriodStop = 10.25*60*60; 

    double myDouble; 
int myInt; 
NSString* myNewString; 
NSString *info; 



      if(time <tenFifteenFirstPeriodStop){ 
     myDouble = (tenFifteenFirstPeriodStop-time)/60; 
     myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5)); 
     myNewString = [NSString stringWithFormat:@"%d", myInt]; 
     info = [[NSString alloc] initWithFormat: 
     @"%@",myNewString]; 
     } 

      NSString *message = [[NSString alloc] initWithFormat: 
        @"%@", info]; 

    UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Minutes Until the Bell   Rings" message:message delegate:nil cancelButtonTitle:@"Great!" otherButtonTitles:nil]; 
[alert show]; 
[alert release]; 
[message release]; 
+2

請嘗試格式化您的代碼 - 它現在看起來幾乎不可讀。 – 2011-06-15 15:34:32

回答

0

這會給你秒鐘的時間,直到今天10.15。如果它已經通過,它將顯示明天10.15秒的時間。

NSDate *today = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
              fromDate:today]; 
[components setMinute:15]; 
[components setHour:10]; 

NSDate * tenFifteenToday = [gregorian dateFromComponents:components]; 
if ([tenFifteenToday timeIntervalSinceNow] < 0) { 
    NSDateComponents * daysToAdd = [[[NSDateComponents alloc] init] autorelease]; 
    [daysToAdd setDay:1]; 

    NSDate * tenFifteenTomorrow = [gregorian dateByAddingComponents:daysToAdd toDate:tenFifteenToday options:0]; 
    NSLog(@"%.0lf", [tenFifteenTomorrow timeIntervalSinceNow]); 
} else { 
    NSLog(@"%.0lf", [tenFifteenToday timeIntervalSinceNow]); 
} 
+0

非常感謝你!我爲我的節目編輯了一下,但是如果沒有你的幫助,我無法完成它,再次感謝 - 凱莉 – 2011-06-15 20:28:08