Sergey Grishchev
Sergey Grishchev

Reputation: 12051

Convert HH:MM NSString to NSInteger with minutes

I have several NSStrings that contains time duration, they look like that: @"03:40", @"08:40" - the time is duration of an action. I want to have an int for each string with minutes, say "01:20" is "80" (minutes) to later compare them with one another.

How do you manage this simple thing in Objective-C? Thanks in advance

EDIT:

Tried this, no avail. I want a totally different approach, something easy and light.

- (NSMutableArray *)sortResultsByTime
{
    NSMutableArray *sortedTrips = [NSMutableArray arrayWithArray:[_tweets sortedArrayUsingComparator: ^(id trip1, id trip2) {

        double time1 = [self durationFromString:[(Tweet *) trip1 flightDuration]];
        double time2 = [self durationFromString:[(Tweet *) trip1 flightDuration]];
        NSLog(@"What's time1? It's %f", time1);
        NSLog(@"What's time2? It's %f", time2);

        if (time1 < time2) {
            return (NSComparisonResult)NSOrderedDescending;
        }

        if (time1 > time2) {
            return (NSComparisonResult)NSOrderedAscending;
        }

        return (NSComparisonResult)NSOrderedSame;
    }]];

    return sortedTrips;
}

- (double)durationFromString:(NSString *)durationString
{
    NSArray *durationArray = [durationString componentsSeparatedByString:@":"];

    return [durationArray[0] doubleValue] + [durationArray[1] doubleValue] / 60.0;
}

Upvotes: 0

Views: 140

Answers (3)

user529758
user529758

Reputation:

I don't see why you consider other answers overcomplicated, but if you want a solution without arrays, here you are:

- (double)durationFromString:(NSString *)s
{
    int hr = 0, min = 0;
    NSScanner *scn = [NSScanner scannerWithString:s];
    [scn scanInt:&hr];
    [scn scanString:@":" intoString:NULL];
    [scn scanInt:&min];
    return hr * 60 + min;
}

Upvotes: 1

rmaddy
rmaddy

Reputation: 318824

The code you posted is attempting to convert the string to the number of hours, not the number of minutes.

You want:

return [durationArray[0] doubleValue] * 60 + [durationArray[1] doubleValue];

Edit: The original code is failing because this line:

double time2 = [self durationFromString:[(Tweet *) trip1 flightDuration]];

needs to be:

double time2 = [self durationFromString:[(Tweet *) trip2 flightDuration]];

Update: Since the OP wants a different approach why not simply do this:

NSString *time1 = [(Tweet *) trip1 flightDuration];
NSString *time2 = [(Tweet *) trip2 flightDuration];

return [time1 compare:time2];

Upvotes: 1

djromero
djromero

Reputation: 19641

Split by : (using -[NSString componentsSeparatedByString:]), access each element (with -[NSArray objectAtIndex:), then convert to integer (-[NSString intValue]) and finally multiply and add.

Upvotes: 1

Related Questions