Will Smith
Will Smith

Reputation: 349

Time Comparison in iPhone

I have an array of times( HH:mm:ss ), how to find out which time is bigger of them and which is elapsed? it will be great if i can sort them by ascending.

Upvotes: 0

Views: 77

Answers (2)

Abid Hussain
Abid Hussain

Reputation: 1549

//COnvert Strings to Dates
//Comparison with current time
NSMutableArray *dates;
for (NSDate *d in dates) {
    if ([d compare:[NSDate date]]== NSOrderedAscending) {
        NSLog(@"Future Time");
    }else if([d compare:[NSDate date]]== NSOrderedSame){
        NSLog(@"Present Time");            
    }else{
        NSLog(@"Past Time");  
    }
}
// For sorting
[dates sortUsingSelector:@selector(compare:)];

Upvotes: 0

user529758
user529758

Reputation:

If your times are given by strings in the HH:mm:ss format, you can convert them to NSDate objects and sort them using a mutable array:

NSArray *timeStrings = // however you obtain it...
NSMutableArray *sorted = [NSMutableArray array];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"HH:mm:ss"];

for (NSString *dtStr in timeStrings) {
    [sorted addObject:[fmt dateFromString:dtStr]];
}

[sorted sortUsingSelector:@selector(compare:)];

Now sorted will contain the date objects sorted asccending.

Upvotes: 1

Related Questions