How can I get the Correct Current Time in iOS?

Meet Doshi picture Meet Doshi · May 30, 2016 · Viewed 10.9k times · Source

I know this it the repeated question. I have reviewed many answers but still didn’t get any solution.

My question is, How can I get the Time of Device if user have set it manually..?

I have implemented one chatting app. But in this app, I have issues of timings. If user have set manually time then how can we identify that.?

I want to get correct current UTC time. So using this, I can identify the difference between device time and UTC time.

If we are using, NSDate *currentDateAndTime = [NSDate date];, then it returns only UTC time according to device, not the current UTC time.

Is there any easy way to find out this solution?

Any help would be appreciated.

Answer

sgl0v picture sgl0v · May 30, 2016

There is no trusted time source in iOS. You just operate with monotonic and non-monotonic time.

Monotonic time (or absolute time) represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. The CACurrentMediaTime() or mach_absolute_time return monotonic time.

Non-monotonic time represents the machine's best-guess as to the current wall-clock, time-of-day time. It can jump forwards and backwards as the system time-of-day clock is changed. The [NSDate date] call returns it.

As an option, you can take the trusted date/time from the http Date response header. Then save it and current monotonic time(CACurrentMediaTime()) in the keychain. Here is the way to get the current trusted time:

last known online time + (CACurrentMediaTime() - saved monotonic time)

Another solution would be to use NTP server.