Home > DeveloperSection > Forums > How to Add two HH:mm:ss in iOS?
Elena Glibart
Elena Glibart

Total Post:33

Points:233
Posted on    October-28-2014 3:09 AM

 iPhone iPhone  Ios  Ios 7 
Ratings:


 1 Reply(s)
 909  View(s)
Rate this:

I tried to look for all possible answers but could not find how to add two times in "HH:mm:ss" format.

I have couple of captured times in an array and I want to return sum of all in HH:mm:ss format as Here is my code:

-(void) addTime

{

   NSMutableArray *recordedArray = [[NSMutableArray alloc]             initWithObjects:@"00:45:12",@"20:08:15",@"00:09:36",@"00:50:20", nil];

   double sumOne = 0;

   for (NSNumber * n in recordedArray)

   {

     sumOne += [n doubleValue];

   }

   NSLog(@"Sum of array time in HH:mm:ss is--> %f", sumOne);

}



Alex Leblois
Alex Leblois

Total Post:67

Points:471
Posted on    October-28-2014 3:14 AM

I got it right here. Was little work but was worth it. Please optimise the code your way before using.

-(void) addTime
 {
    NSMutableArray *recordedArray = [[NSMutableArray alloc] initWithObjects:@"00:00:24",@"00:08:12",@"00:09:36",@"01:30:25", nil];
    captureAllSecondsArray = [[NSMutableArray alloc] init];// Define NSMutableArray * captureAllSecondsArray in your .h file.
    for (int i = 0; i<[recordedArray count]; i++)
    {
      [captureAllSecondsArray addObject:[self dateToSecondConvert:[recordedArray objectAtIndex:i]]];
    }
     int sumOfArray = 0;
     for (NSNumber * n in captureAllSecondsArray)
     {
       sumOfArray += [n intValue];
     }
     NSString *iCanUseThis= [NSString stringWithFormat:@"%@", [self timeFormatted:sumOfArray]];
     NSLog(@"Sum of array time in HH:mm:ss is--> %@",iCanUseThis);
 }
 - (NSNumber *)dateToSecondConvert:(NSString *)string
  {
    NSArray *components = [string componentsSeparatedByString:@":"];
    NSInteger hours   = [[components objectAtIndex:0] integerValue];
    NSInteger minutes = [[components objectAtIndex:1] integerValue];
    NSInteger seconds = [[components objectAtIndex:2] integerValue];
    NSNumber *secondsNumber = [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];
    return secondsNumber;
  }
- (NSString *)timeFormatted:(int)totalSeconds
 {
   int seconds = totalSeconds % 60;
   int minutes = (totalSeconds / 60) % 60;
   int hours = totalSeconds / 3600;
   NSString *totalTime = [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
   return totalTime;
 }

Don't want to miss updates? Please click the below button!

Follow MindStick