开发者

NSString to NSDate with float values

开发者 https://www.devze.com 2023-01-15 06:31 出处:网络
I\'m developing an OS X desktop application whic开发者_运维知识库h will track time for a car racing event.

I'm developing an OS X desktop application whic开发者_运维知识库h 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!)

0

精彩评论

暂无评论...
验证码 换一张
取 消