4

anyone know or can provide some example code relating to "timeIntervalSinceNow" method...

I need something like... time2(when app eneters foreground) - time1(when app enters background) = time3(the difference in times)... this is so i can use this number(pref in seconds) to calculate the time i have lost while the app has been in background !!

I am having trying trying to create the date objects, receive the object and display/use in a label....

Aleš
  • 8,896
  • 8
  • 62
  • 107
myles
  • 75
  • 1
  • 1
  • 8

3 Answers3

4

Actually, to answer your original question, myles, you can use timeIntervalSinceNow. In the statement below, inputDate has been initialized as an NSDate and set to some date (you could just try [NSDate *inputDate = [NSDate date]; to set the date at the current date and time.

NSTimeInterval timeToAlert =[inputDate timeIntervalSinceNow];

The next line is a way to put that NSTimeInterval into a string.

NSMutableString *timeinterval = [NSMutableString string];
[timeinterval appendFormat:@"%f",timeToAlert];

Finally, the app delegate class is typically where code can be written to handle coming in and out of background. Good luck!

Emil
  • 7,220
  • 17
  • 76
  • 135
bob s
  • 41
  • 1
3

timeIntervalSinceNow tells you the offset of an NSDate from the current time. You want timeIntervalSinceDate::

NSDate *appEnteredForeground = ...;
NSDate *appEnteredBackground = ...;

NSTimeInterval difference = [appEnteredBackground timeIntervalSinceDate: appEnteredForeground];
Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
  • it keeps saying "Unused variable 'difference'" i dont know how to get the value from difference and put it into a label. btw should i be doing this in the delegate's ?? many thanks for the help dude !! – myles May 26 '11 at 22:02
  • 3
    It sounds like you might need to take a step back and learn the basics of C and Objective-C before diving headlong into UI design. :) – Jonathan Grynspan May 26 '11 at 23:24
3

You can calculate the difference between two dates with the timeIntervalSinceDate: method:

//When app enters background:
self.backgroundDate = [NSDate date]; //this should be a property 
//...
//When the app comes back to the foreground:
NSTimeInterval timeSpentInBackground = [[NSDate date] timeIntervalSinceDate:self.backgroundDate];

NSTimeInterval is simply a typedef for double, it's measured in seconds. [NSDate date] instantiates an NSDate object with the current date and time.

omz
  • 53,243
  • 5
  • 129
  • 141
  • how do i create a property for backgroundDate ?? – myles May 26 '11 at 21:24
  • [The Objective-C Programming Language – Declared Properties](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17) – omz May 26 '11 at 21:29