Adding times
Hi everybody,
I have just started out with cocoa and I am trying to make a flying logbook application where I will add each of my flights with their details and then have the application add the hours etc up to give me a total!
I have decided to use core data (please comment if people think there is a better method for this sort of application). So one of the attributes is time flown on the particular flight and tried setting this to the date type but this seems only to want to deal with time in the sense of minutes hours days weeks months years etc. which is not how I want to use it I require to be able to enter a flight time as 1:30 then the next as 0:30 etc. then at the end add it up to give me a total of 2hours, I also want to be able to add time over 24 hours eg. 26:30 which i can't do with the current setup I have.
Thanks
See http://stackoverflow.com/questions/1990175 for answer.
(Just posting this as I hate unfinished threads when I'm looking for answers)
I think there's a simpler way to deal with this. The NSDate object can has methods for calculating NSTimeInterval between dates.
The other observation is that while you can enter times such as 1:30, you should simply convert that to seconds and maybe you're done!
The following command-line program NSDate and NSTimeInterval being being used. The constructor can even parse the time in common formats (eg 03:15:07 for 3hrs, 15mins, 7secs.
#import <Foundation/Foundation.h>
static void getHMS(NSTimeInterval dt,int* h,int* m,int* s)
{
long D = (long) dt ;
int H = D / 3600 ;
D-= H * 3600 ;
int M = D / 60 ;
D-= M * 60 ;
int S = D ;
*h = H ;
*m = M ;
*s = S ;
}
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// insert code here...
NSLog(@"Hello, World!");
long delta = 26 * 3600 + 3 * 60 + 15 ;
NSDate* t1 = [[NSDate alloc]init] ;
NSLog(@"%@",t1) ;
NSDate* t2 = [NSDate dateWithTimeInterval:delta sinceDate: t1] ;
NSLog(@"%@",t2) ;
NSTimeInterval dt = [t2 timeIntervalSinceDate:t1] ;
int h, m, s ;
getHMS(dt,&h,&m,&s);
NSLog(@"delta time = %f seconds = %d:%d:%d",dt,h,m,s) ;
NSDate* t3 = [NSDate dateWithNaturalLanguageString:@"00:00:00"];
NSDate* t4 = [NSDate dateWithNaturalLanguageString:@"03:15:07"];
getHMS([t4 timeIntervalSinceDate:t3],&h,&m,&s);
NSLog(@"delta time = %f seconds = %d:%d:%d",dt,h,m,s) ;
[pool drain];
return 0;
}
Output
2010-01-20 18:54:23.976 Dates[3933:a0f] Hello, World!
2010-01-20 18:54:23.983 Dates[3933:a0f] 2010-01-20 18:54:23 -0800
2010-01-20 18:54:23.984 Dates[3933:a0f] 2010-01-21 20:57:38 -0800
2010-01-20 18:54:23.984 Dates[3933:a0f] delta time = 93795.000000 seconds = 26:3:15
2010-01-20 18:54:23.985 Dates[3933:a0f] delta time = 93795.000000 seconds = 3:15:7