Question

Possible Duplicate:
hours minutes seconds to seconds ios

I have a time formatted as such

// format: HH:mm:ss,AAA
// example for 2 hours, 35 minutes, 15 seconds, and 207 milliseconds
02:35:15,207

I'm trying to convert that into seconds as a double. The above example would turn into:

// 2 hrs * 3600 + 25 min * 60 + 15.207
9315.207

I figure I can pick apart each element with a scanner, but I'm thinking there's probably an easier way. I tried using NSDateFormatter but I need this as a double, not as an NSDate. Any suggestions? Thanks.

Further FYI

This is for use with the MPMoviePlayer and the currentTime property is a double. For any given section where I have data to show, I am checking if dataStartTime <= playerTime < dataEndTime. So I'm using double because that's the type for currentTime already.

Was it helpful?

Solution

Here is the solution, the idea is simple get two date one with your time and one with 00:00:00,000 time then take difference of their time.

- (double)secondsFromString:(NSString*)str {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss,SSS"];
    NSString *dateString = @"1970-01-01";
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%@ %@",dateString,str]];
    NSDate *refDate = [formatter dateFromString:[NSString stringWithFormat:@"%@ 00:00:00,000",dateString]];
    double time = [date timeIntervalSince1970] - [refDate timeIntervalSince1970];
    return time;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top