Search code examples
iphoneobjective-cnsdatenstimeinterval

how to compare time with current date and time?


In My application I have to complete a particular task in given time.So first i calculated the time complete the task in seconds and then add that time to the current that like this.

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

now I compare time like this

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

but I want to know is Time is left or not.Is current time is less then or greater then current time how can i know this ?


Solution

  • I have an example where I get the time from a picker and check if its today or tomorrow. You should be able to just take the code and use it in your way...

    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");
    }