Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

Here's the code I use.

In my app, when the user syncs some data, I record the current date/time using this code:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSDate date] forKey:@"LastSyncDate"];
[prefs synchronize];

Then, if I want to see how many days it's been since they last synced, I can use this:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSDate* dateOfLastSync = [prefs objectForKey:@"LastSyncDate"];
if (dateOfLastSync != nil)
{
    NSDate *timeNow = [NSDate date];
    double SECONDS_TO_DAY = 60 * 60 * 24;
    int timeIntervalInDays = (int)([timeNow timeIntervalSinceDate:dateOfLastSync] / SECONDS_TO_DAY);
    NSLog(@"The last sync was %d days ago.", timeIntervalInDays);
}

Hope this helps.

Mike

www.MikesKnowledgeBase.com

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

double timeInterval = [timeNow timeIntervalSinceDate:timeSaved];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top