Take the 2-minute tour ×

Here's the scenario:

  1. My app is running, it calls some function to get the current time and writes this time to a persistent database (i.e. on disk)
  2. I force kill my app and power off my iPhone
  3. Daylight savings has come and gone AND I've flown half way around the wold and crossed the international date line.
  4. I turn on my iPhone and run my app
  5. My app reads the time in the database, calls a function to get the current time and calculates the truly elapsed time in seconds/millisecond/etc. accounting for time zone, date line and DST changes.

On iOS using C/Objective-C what function(s) do I need to call to get the current time that will allow me to calculate the truly elapsed time?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

For step 1, you do this:

NSDate *currentTime = [NSDate date];

Alternatively, if you don't want an object and want a double value, you can do this:

NSTimeInterval currentTimestamp = [NSDate timeIntervalSinceReferenceDate];

Then, in step 5, you do the exact same thing again:

NSTimeInterval timeInTheDatabase = ...
NSTimeInterval currentTimestamp = [NSDate timeIntervalSinceReferenceDate];

The truly elapsed time then is this:

NSTimeInterval elapsedTime = currentTimestamp - timeInTheDatabase.

This will give you the number of seconds between the first and second times.

Why does this work?

It works because NSDates are always in GMT. The "conversion" to your timezone doesn't happen until it gets formatted for display via an NSDateFormatter.

share|improve this answer

Its better to use timeIntervalSinceDate: its more straight forward:

for step 1, you get the current Date and you store it:

NSDate *storedDate = [NSDate date];

And when you'd want to get the elapsed time you use this:

float elapsedTime = [NSDate timeIntervalSinceDate:storedDate];

I think it's better than getting the elapsed time since the first instant of 1 January 2001, GMT (timeIntervalSinceReferenceDate), and doing the computation...

share|improve this answer

Your Answer


