Pages

September 12, 2013

Check if a string is a valid time format

Ever wonder to check if a NSString might represent a valid time? I mean, hours : minutes : seconds ...


/** Check whether a string is a valid time in standard format "HH:mm:ss".

 @param time String time to evaluate.
 @return Returns true if it's a valid string time, false otherwise.

 */
+ (BOOL)isValidTimeString:(NSString *)time {

    NSArray *temp = [time componentsSeparatedByString:@":"];
    if ([temp count] != 3) { return NO;    }

    NSString *h = [temp objectAtIndex:0];
    NSString *m = [temp objectAtIndex:1];
    NSString *s = [temp objectAtIndex:2];

    // Minutes and seconds must be of two digits. Hours, instead, might have any digits.
    if (m.length != 2) { return NO;    }
    if (s.length != 2) { return NO;    }

    // Check values are numeric.
    NSCharacterSet *num09 = [NSCharacterSet decimalDigitCharacterSet];
    if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:h]]) { return NO; }
    if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:m]]) { return NO; }
    if (![num09 isSupersetOfSet:[NSCharacterSet characterSetWithCharactersInString:s]]) { return NO; }

    // Minute and second values must be lesser than 60.
    if ([m integerValue] >= 60) { return NO; }
    if ([s integerValue] >= 60) { return NO; }

    return YES;
}



Download the ready-for-use source file (.m) of Check if a string is a valid time format

No comments:

Post a Comment