Search code examples
iosobjective-cnsstringnstimeinterval

How to add two Strings, string having TimeIntervals?


I have two strings with time interval data. I want to add that two time intervals and store into another string. This is my data

NSString *oldTime=@"00:24";         //Time format is "mm:ss"


NSString *newTime=@"00:07";         //Time format is "mm:ss"

After adding two strings i need to store that total time in another string like below

NSString *totalTime=oldTime+newTime;        //(totalTime=00:31)  

I am fresher to iOS so please send me the code for this problem. Thanks in advance


Solution

  • I don't know this is perfect solution. But this will work

        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"mm:ss"];
    
        NSDate *date = [df dateFromString:@"00:00"];
        NSDate *date1 = [df dateFromString:@"00:24"];
        NSDate *date2 = [df dateFromString:@"00:07"];
    
        NSTimeInterval interval1 = [date1 timeIntervalSinceDate:date];
        NSTimeInterval interval2 = [date2 timeIntervalSinceDate:date];
    
        NSDate *addedDate = [date dateByAddingTimeInterval:interval1+interval2];
    
        NSString *resultDate = [df stringFromDate:addedDate];
    

    Hope this helps.