2011-09-10 1 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

나는 선택기에서 시간을 얻고 오늘 또는 내일을 확인하는 예제가 있습니다. 코드를 가져 와서 사용할 수 있어야합니다.

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에 대한 몇 가지 방법이 있습니다 - 제공된있는 NSDate 객체와 2001년 1월 1일 사이의 시간 차이를 반환 2001년 1월 1일, -timeIntervalSinceReferenceDate, -timeIntervalSinceDate:, 이후의 초 수를 반환 +timeIntervalSinceReferenceDate는 어떤 두 NSDate 객체 사이의 차이 (초)를 반환하고 -timeIntervalSinceNow은 현재 시간과 NSDate 객체 간의 차이를 반환합니다.

NSDate 값을 NSTimeInterval로 대신 저장하는 것이 가장 편리합니다 (예 : timeIntervalSinceReferenceDate). 이렇게하면 유지 및 처분 할 필요가 없습니다.