Adding elapsed time in Cocoa
In Cocoa, how would I add times for example:
1:30 (one hour and 30 minutes) 1:25 (one hour and 25 minutes) 2:15 (two hour and 15 minutes)
= 5:10
but when I get to greater then 24 hours I do not want it to go, one day x hours and y mins, I want it to continue adding the hours e.g. 25, 26, 27 ... 1开发者_C百科00 hours etc. Is there already an implemented method in Cocoa?
Thanks
Add them yourself in a date components object.
When you add two seconds components together, divide by 60 to determine the number to carry to the minutes component, and use the %
operator to determine the new value of the seconds component. (For example, 73 seconds is 73 / 60
= 1 minute and 73 % 60
= 13 seconds.) Do likewise for adding minutes and carrying to hours. Then, when adding hours, just add them and don't do any divmod magic if you don't want to carry to the days component.
See the Date and Time Programming Guide.
Just for other peoples interest using Peter Hoseys advice heres my simple command line tool which solves this problem: (if anyone has any tips for bettering my solution it would be very much appreciated). Also is there any advantage to using the remainder function
over the %
?
#import <Foundation/Foundation.h>
NSDateComponents *totalTime;
void timeByAddingComponents(NSDateComponents *firstTime, NSDateComponents *secondTime) {
int addMin = [firstTime minute] + [secondTime minute];
int addHour = floor(addMin/60);
addMin = addMin % 60;
addHour = addHour + [firstTime hour] + [secondTime hour];
[totalTime setMinute:addMin];
[totalTime setHour:addHour];
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
totalTime = [[NSDateComponents alloc] init];
[totalTime setHour:0];
[totalTime setMinute:0];
NSDateComponents *addTime = [[NSDateComponents alloc] init];
while (TRUE) {
int x, y;
printf("Please Enter Number of Hours: ");
scanf("%d", &x);
printf("Please Enter Number of Minutes: ");
scanf("%d", &y);
if (x == 0 && y == 0)
break;
NSLog(@"Add %i:%i to %i:%i", x,y, [totalTime hour], [totalTime minute]);
[addTime setHour:x];
[addTime setMinute:y];
timeByAddingComponents(totalTime, addTime);
NSString *time = [NSString stringWithFormat:@"%.2d:%.2d",[totalTime hour],[totalTime minute]];
NSLog(@"Total time now: %@", time);
}
[totalTime release];
[addTime release];
[pool drain];
return 0;
}
If I am only using this time for the purposes of adding to gain a total, would it be better to use a C Sturct like below then NSDateComponents?
typedef struct {
int hours;
int minutes;
} time;
精彩评论