如何在 iOS 中获取正确的当前时间? [英] How can I get the Correct Current Time in iOS?

查看:99
本文介绍了如何在 iOS 中获取正确的当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是重复的问题.我查看了很多答案,但仍然没有得到任何解决方案.

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.?

我想获得正确的当前 UTC 时间.所以使用这个,我可以识别设备时间和 UTC 时间之间的差异.

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

如果我们使用,NSDate *currentDateAndTime = [NSDate date];,那么它只根据设备返回UTC时间,而不是当前UTC时间.

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?

任何帮助将不胜感激.

推荐答案

iOS 中没有可信的时间源.您只需使用单调和非单调时间即可.

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

单调时间(或绝对时间)表示自过去某个任意固定点以来经过的绝对挂钟时间.CACurrentMediaTime()mach_absolute_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.

非单调时间代表机器对当前挂钟、时间的最佳猜测.它可以随着系统时钟的改变而向前和向后跳跃.[NSDate date] 调用返回它.

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.

作为一种选择,您可以从 http Date 响应标头中获取受信任的日期/时间.然后将它和当前单调时间(CACurrentMediaTime())保存在钥匙串中.以下是获取当前可信时间的方法:

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:

最后已知的在线时间 + (CACurrentMediaTime() - 保存的单调时间)

另一种解决方案是使用 NTP 服务器.

Another solution would be to use NTP server.

这篇关于如何在 iOS 中获取正确的当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆