Sri
Sri

Reputation: 454

how to add the time in iphone?

I have three string

str1 = @"00:14"; str2 = @"00:55"; str3 = @"00:10";

i need to add the three string as a integer and display in the same time format

how can i do please help me

Thanks in Advance

Upvotes: 0

Views: 233

Answers (3)

danjonweb
danjonweb

Reputation: 456

Working with dates in Cocoa is fun! You could create a method like this:

- (NSDate *)dateByAddingDates:(NSArray *)dates {
  NSCalendar *calendar = [NSCalendar currentCalendar];
  unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
  NSDate *date = [dates objectAtIndex:0];
  for (int i = 1; i < [dates count]; i++) {
    NSDate *newDate = [dates objectAtIndex:i];
    NSDateComponents *comps = [calendar components:unitFlags fromDate:newDate];
    date = [calendar dateByAddingComponents:comps toDate:date options:0];
  }
  return date;
}

And use it like this:

  NSString *str1 = @"00:14";
  NSString *str2 = @"00:55";
  NSString *str3 = @"00:10";

  NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
  [dateFormatter setDateFormat:@"mm:ss"];

  NSArray *dates = [NSArray arrayWithObjects:[dateFormatter dateFromString:str1],
                    [dateFormatter dateFromString:str2],
                    [dateFormatter dateFromString:str3], nil];
  NSDate *date = [self dateByAddingDates:dates];

  NSLog(@"%@", [dateFormatter stringFromDate:date]);

Upvotes: 2

evandrix
evandrix

Reputation: 6210

check out this related thread: Comparing dates

in summary, first parse the strings as NSDates using the initWithString: method call. Thereafter you can add and manipulate the dates any way you wish, and finally just format it for the right output.

Hope this hopes clarify your query.

Btw the Mac Developer SDK Reference can found here for your information:- http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDate

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243156

To do things properly, it would be this:

  • Use an NSDateFormatter to convert the strings into NSDate objects.
  • Use [NSCalendar currentCalendar] to extract the NSDateComponents for each date, particularly the NSMinuteCalendarUnit.
  • Add up all the minutes of the date components, and set that into an NSDateComponent object
  • (optional) Use your calendar to convert the NSDateComponent back into an NSDate.

To do things stupidly, you'd get a substring of characters after :, invoke intValue on it to turn the string into an int, then add it all up. I don't recommend doing this, because it could lead to subtle and devious errors. Plus, there's already code in place to do it for you. :)

Upvotes: 0

Related Questions