开发者

how to add the time in iphone?

I have three string

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

i n开发者_高级运维eed 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


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]);


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. :)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜