How can I get the Correct Current Time in iOS?
Solution 1
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.
Solution 2
This might solve your problem
NSDate * date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *currentTime = [dateFormatter stringFromDate:date];
NSLog(@"current time is:%@",currentTime);
Comments
-
Meet Doshi over 1 year
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.
-
Meet Doshi almost 8 yearsIt is not working, if you are setting manually time without using any time zone. It will returns on device time with UTC time.
-
Nicolas Buquet almost 8 yearsDevice always works using UTC time. Only the display of time use timeZone precision, but for display only.