简体   繁体   中英

NSString to NSDate with float values

I'm developing an OS X desktop application which will track time for a car racing event.

The difference between pilots can be very small, so the collected data for each lap has a floating point value for the seconds:

bestLap = @"00:01:39.5930000"

But I need to compare each pilot's time and sort it. I'm trying to convert it to a NSDate object, using NSDateFormatter and I couldn't manage to make it work

Is it possible to convert a string like that to a NSDate? If so, how can I compare and sort an array containing NSDates

Thanks

An NSDate is used to represent a date , not a time interval.

Also, if the purpose is just to sort them, there is no need to convert the string into an NSDate or NSTimeInterval since they are already lexicographically ordered if a time interval is shorter than the other in your format.

That means, calling -sortUsingSelector: is enough.

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

As KennyTM says, lexicographic sorting is enough if all you need is ordering. If you really want to get a numeric value for comparison & reporting purposes, you can break the string up into components and convert to a double something like this:

NSArray* parts = [bestLap componentsSeparatedByString:@":"];
double bestLapInSeconds = [[parts objectAtIndex:0] doubleValue] * 3600    // hours
                          + [[parts objectAtIndex:1] doubleValue] * 60    // minutes
                          + [[parts objectAtIndex:2] doubleValue];        // seconds

(Note that this just blithely assumes that the original string conforms to an "H:M:S" format without any error checking. You should not normally do this in real life!)

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