简体   繁体   中英

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

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];

分割为:使用-[NSString componentsSeparatedByString:] ),访问每个元素(使用-[NSArray objectAtIndex: ,然后转换为整数( -[NSString intValue] ),最后相乘并相加。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM