views:

936

answers:

2

Hi guys - last resort this as I cannot for the life of me work it out!

I am setting a date when my app is closed (using applicationWillTerminate) in user defaults

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *timeClosed = [[NSDate alloc] init];
[defaults setObject: timeClosed forKey:@"svdTimeClosedApp"];

then when the app is launched, I want to compare this time using

NSDate *timeSaved = svdTimeClosedApp;
NSDate *timeNow = [[NSDate alloc] init];
double timeInterval = [timeSaved timeIntervalSinceDate:timeNow];
NSLog(@"time now = %@, time saved = %@, time diff = %@", timeNow, timeSaved, [NSString stringWithFormat:@"%d",timeInterval]);

I tried to output this to the log window expecting to see a nicely formatted string of around 20 seconds. Trouble is, it's coming out as 2047868928!

Any ideas?!

(output of the log window below)

time now = 2009-12-19 20:54:02 +0000, time saved = 2009-12-19 20:48:29 +0000, time diff = 2047868928

Thanks for any help!

A: 

I think you have your timeInterval calculation backwards, don't you? I think you want to say it reversed.

double timeInterval = [timeNow timeIntervalSinceDate:timeSaved];
Marc W
I did try that, the result wastime now = 2009-12-19 21:28:28 +0000, time saved = 2009-12-19 21:28:24 +0000, time diff = -201326592Given that there was 4 seconds shown - I would assume time diff should be 4. I'm wondering whether I need to format the dates to strings first to get the hours, minutes and seconds...
Matt Facer
+1  A: 

there are a couple of issues. First, in your stringWithFormat: you want to use %g, not %d, %d is for integer values. Also, you should do [timeNow timeIntervalSinceDate:timeSaved] your current call will give you a negative value.

Elfred
that's done it! [time diff = 4.71526] - it was the stringwithformat that wasn't correct. Can't believe that's all it was!Thanks very much guys!
Matt Facer