现有的Obj-C函数用于转换字符串,例如" 1m"," 1h"," 1d"到NSTimeInterval?

时间:2017-05-16 18:47:35

标签: ios objective-c

我有一个要解析的字符串包含时间段为" 1ms"," 1s"," 1m"," 1h& #34;," 1d"," 1w"," 1y"。

我可以纹理地解析它并使用case语句而不会有太多的麻烦,但我想知道是否有一种现有的便利方法我可以用来代替它?

*** 30分钟后我的问题没有答案,所以我花时间从头开始创建一个粘贴在下面的功能。仍然想知道是否有内置函数执行此操作

- (NSTimeInterval) convertStringToNSTimeInterval:(NSString*) string
{
    int digitCount = 0;
    NSInteger charIdx = 0;
    for (; charIdx<string.length; charIdx++)
    {
        unichar c = [string characterAtIndex:charIdx];
        if(c >='0' && c <='9')
        {
            ++digitCount;
        }
    }
    NSString* baseString = [string  substringToIndex: digitCount];
    double base = [baseString doubleValue];
    NSString* timeUnit = [string substringFromIndex:digitCount];

    if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"Y"])
    {
        base *= 365.242199;
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"D"])
    {
        base *= (24 * 60 * 60);
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"H"])
    {
        base *= (60 * 60);
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"M"])
    {
        base *= 60;
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"S"])
    {
        // Already in seconds
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"W"])
    {
        base *= (7 * 24 * 60 * 60);
    }
    else if (NSOrderedSame == [timeUnit caseInsensitiveCompare:@"MS"])
    {
        base /= 1000;
    }

    NSTimeInterval result = base;
    [Model log: [NSString stringWithFormat: @"convertStringToNSTimeInterval. Converting from: %@", string]];
    [Model log: [NSString stringWithFormat: @"convertStringToNSTimeInterval. result: %f seconds", result]];
    return result;
}

0 个答案:

没有答案