Pages

September 17, 2013

Get the number of seconds in a time string

How many seconds there are in a given time string value?


/** Converts from string time to seconds.

 Works only if used with this time format "HH:mm:ss".

 @param str Time string in format "HH:mm:ss".
 @return Returns the total number of seconds as NSNumber.
 @see stringTimeFromSeconds:

 */
+ (NSNumber *)secondsInTimeString:(NSString *)str {
    NSNumber *ret = [NSNumber numberWithLong:-1];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:[str componentsSeparatedByString:@":"]];
    if ([tempArr count] == 3) {
        ret = [NSNumber numberWithLong: [[tempArr objectAtIndex:0] integerValue]*60*60 + [[tempArr objectAtIndex:1] integerValue]*60 + [[tempArr objectAtIndex:2] integerValue] ];
    }
    return ret;
}



Download the ready-for-use source file (.m) of Get the number of seconds in a time string

No comments:

Post a Comment