Search code examples
iosnsstringnsscanner

Convert string to timer, and add 1 minute to the string


If I have a string from key and the string is a timer (12:00) how to add 1 minute to the timer, so the label will show 12:01:

NSString string = [subDict objectForKey:@"1"];

NSScanner timeScanner=[NSScanner scannerWithString:string];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:@":" intoString:nil]; 
[timeScanner scanInt:&minutes];

Thanks


Solution

  • Make sure to take care of the carry. As to a simple solution, you don't even need a scanner:

    NSString *timeStr = @"23:59";
    
    NSArray *comps = [timeStr componentsSeparatedByString:@":"];
    int h = [comps[0] intValue];
    int m = [comps[1] intValue];
    
    h += (m + 1) / 60;
    h %= 24;
    
    m = (m + 1) % 60;
    
    NSLog(@"The new time is: %02d:%02d", h, m);