[Solved] How to compare two time from NSDate. Returning nil for nsdate when doing comparision. #debug my code


There was a typo:
[dateFormatter setDateFormat:@"HH:mm:ss"];
should be:
[formatter setDateFormat:@"HH:mm:ss"];

To compare two dates use:

NSDate *date1 = [NSDate date];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date2 = [formatter dateFromString:@"05:00:00"];

NSComparisonResult result = [date1 compare:date2];
if(result == NSOrderedDescending)
{
    NSLog(@"date1 is later than date2");
}

If you only want to compare the hours:

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDate *date1 = [NSDate date];
NSDateComponents *date1Components = [calendar components:NSCalendarUnitHour fromDate:date1];
NSInteger date1Hour = date1Components.hour;

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSDate *date2 = [formatter dateFromString:@"05:00:00"];
NSDateComponents *date2Components = [calendar components:NSCalendarUnitHour fromDate:date2];
NSInteger date2Hour = date2Components.hour;

if(date1Hour > date2Hour) {
    NSLog(@"date1 is later than date2");
}

5

solved How to compare two time from NSDate. Returning nil for nsdate when doing comparision. #debug my code