NSString到TimeInterval

时间:2012-12-06 16:25:31

标签: objective-c ios

我有一个格式为00:00:00.00的NSString,最初来自[dateFormatter setDateFormat:@"HH:mm:ss.SS"];

如何获取该字符串并将其转换为TimeInterval?

2 个答案:

答案 0 :(得分:6)

如果你100%绝对肯定这种格式不会改变,那么这里是一个在Cocoa中使用one of the most useful classes的快速解决方案:

- (NSTimeInterval)timeFromString:(NSString *)str
{
    NSScanner *scn = [NSScanner scannerWithString:str];

    int h, m, s, c;
    [scn scanInt:&h];
    [scn scanString:@":" intoString:NULL];
    [scn scanInt:&m];
    [scn scanString:@":" intoString:NULL];
    [scn scanInt:&s];
    [scn scanString:@"." intoString:NULL];
    [scn scanInt:&c];

    return h * 3600 + m * 60 + s + c / 100.0;
}

答案 1 :(得分:1)

我明白了。比我想象的要简单得多:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss.SS"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSDate *currentDate = [dateFormatter dateFromString:finishTimeString];
    NSTimeInterval interval = [currentDate timeIntervalSince1970];