2010-09-08 167 views
1

我一直想知道如何顯示未來某個日期的剩餘時間。Iphone SDK:如何從當前時間倒數到未來的特定日期

這就是我到目前爲止。我可以得到當前時間,並顯示出來,並且我使用了午夜教程的分鐘數來找出如何找出午夜的時間。但我很想知道我將來如何選擇一天,並找出剩下多少時間。

代碼:

NSDate* now = [NSDate date]; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

    NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now]; 

    NSInteger hour = 23 - [dateComponents hour]; 
    NSInteger minute = 59 - [dateComponents minute]; 
    NSInteger second = 59 - [dateComponents second]; 
    [gregorian release]; 
    countdownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour, minute, second]; 

的任何可能性,有人可以看看這個,改變它一點?如果我能夠通過使用這些代碼來理解它,這對我來說是最容易的,但如果這不可能或不正確,我寧願知道正確的方法來做到這一點。

謝謝。

回答

2

嘗試其中之一,這將是第二兩個日期之間數上雙:

NSTimeInterval timeBetweenThenAndNow = [futureDate timeIntervalSinceNow]; 
NSTimeInterval timeBetweenThenAndMidnight = [futureDate timeIntervalSinceDate: myMidnightDate]; 
+0

對不起,誤會,但你能更具體在何處,我應該嘗試這些? – 2010-09-08 21:59:34

+0

您應該使用這些來獲取一個日期與另一個日期之間或現在與另一個日期之間的時間長度。 NSDateFormatter將幫助打印結果,這是NSTimeInterval - 之間的秒數。看看課堂參考資料,並告訴我更多關於如果你仍然陷入困境,你想要做什麼。 – 2010-09-08 22:59:20

+0

好吧,嗯仍然有點卡住了,但我想我知道需要發生什麼,我只是想把它放在一起。我需要定義兩個單獨的日期。其中一個是我現在可以使用的時間? - NSDate *現在= [NSDate日期]; - 然後我需要在將來設置日期2010年9月15日(可能看起來像這樣? - NSDateFormatter * dateformatter = [[NSDateFormatter alloc] init]; [dateformatter setDateFormat:@「MM/dd/yyyy hh:mm:ss「]; NSString * future = [[NSString alloc] initWithString:@」09/15/2010 12:00:00 am「]; - )我想一個例子會有所幫助。 – 2010-09-09 19:27:53

相關問題