2011-09-10 94 views
0

在我的應用程序中,我必須在給定的時間內完成一項特定的任務。因此,我首先計算完成任務的時間,然後將時間添加到像這樣的當前時間。如何比較當前日期和時間?

NSDate *mydate = [NSDate date]; 
NSTimeInterval TotalDuraionInSec = sec.cal_time * 60; 
TaskCmpltTime = [mydate addTimeInterval:TotalDuraionInSec]; 
NSLog(@"task will be completed at%@",TaskCmpltTime); 

現在我比較時這樣

if([CurrentTime isEqualToDate:AfterCmpltTime]){ 
NSLog (@"Time Finish"); 
} 

,但我想知道的是時間是左還是not.Is當前時間是小於或大於當前的時間,我怎麼能知道呢?

回答

0

我有一個例子,我從picker中得到時間,並檢查它是否在今天或明天。你應該能夠只取代碼,並在您的方式使用它...

int selectedHour = [customPickerView selectedRowInComponent:0]; 
int selectedMinute = [customPickerView selectedRowInComponent:1]; 

NSDate *today = [NSDate date]; 
NSDateFormatter *weekdayFormatter = [[[NSDateFormatter alloc] init]autorelease]; 
NSDateFormatter *hmformatter = [[[NSDateFormatter alloc] init]autorelease]; 
[hmformatter setDateFormat: @"hh mm"]; 
[weekdayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4]; 
[weekdayFormatter setDateFormat: @"EE"]; 
// NSString *formattedDate = [formatter stringFromDate: today]; 


NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease]; 
NSDateComponents *dateComponentsToday = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit) fromDate:today]; 


NSInteger currentHour = [dateComponentsToday hour]; 
NSInteger currentMinute = [dateComponentsToday minute]; 

NSString *weekday; 



if ((selectedHour > currentHour) | ((selectedHour == currentHour) & (selectedMinute > currentMinute))) { 
    //so we are still in today 
    weekday = [weekdayFormatter stringFromDate: today]; 
    weekday = NSLocalizedString(@"today", @"today"); 
} else { 
    //the timer should start tomorrow 
    NSTimeInterval secondsPerDay = 24 * 60 * 60; 
    NSDate *tomorrow = [today dateByAddingTimeInterval:secondsPerDay]; 
    weekday = [weekdayFormatter stringFromDate: tomorrow]; 
    weekday = NSLocalizedString(@"tomorrow", @"tomorrow"); 
} 
1

timeIntervalSinceNow將NSDate與Now進行比較。如果NSDate在現在返回值是正的,如果日期早於現在結果是負的。

double timeLeft = [TaskCompltTime timeIntervalSinceNow]; 

if( timeLeft > 0.0) 
// still time left 

else 
    //time is up 
0

呀,你的目的,可能是最好的時間間隔工作。 Objective-C中的NSTimeInterval是double的別名,它代表以秒爲單位的時間值(當然還有分數,至少爲毫秒分辨率)。

有上的NSDate幾種方法用於此 - +timeIntervalSinceReferenceDate,由於2001年1月1日,-timeIntervalSinceReferenceDate,它返回所供應的NSDate對象和2001年1月1日之間的時間差,-timeIntervalSinceDate:,它返回的秒數,其返回兩個NSDate對象和-timeIntervalSinceNow之間的差值(以秒爲單位),它返回當前時間和NSDate對象之間的差異。

很多時候將NSDate值存儲爲NSTimeInterval(例如,timeIntervalSinceReferenceDate)是最方便的。這樣它不必保留和處置等。

相關問題