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 intoNSDate
objects. - Use
[NSCalendar currentCalendar]
to extract theNSDateComponents
for each date, particularly theNSMinuteCalendarUnit
. - 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 anNSDate
.
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
精彩评论