如何在iOS中获取正确的当前时间?

如何在iOS中获取正确的当前时间?,ios,objective-c,swift,time,nstimezone,Ios,Objective C,Swift,Time,Nstimezone,我知道这是一个重复的问题。我已经复习了很多答案,但仍然没有得到任何解决方案 我的问题是,, 如果用户手动设置了设备的时间,如何获取设备的时间 我已经实现了一个聊天应用程序。但在这个应用程序中,我遇到了时间问题。如果用户手动设置了时间,那么我们如何识别它 我想获得正确的当前UTC时间。因此,使用这个,我可以识别设备时间和UTC时间之间的差异 如果我们使用,NSDate*currentDateAndTime=[NSDate-date],则根据设备仅返回UTC时间,而不是当前UTC时间 有什么简单的方

我知道这是一个重复的问题。我已经复习了很多答案,但仍然没有得到任何解决方案

我的问题是,, 如果用户手动设置了设备的时间,如何获取设备的时间

我已经实现了一个聊天应用程序。但在这个应用程序中,我遇到了时间问题。如果用户手动设置了时间,那么我们如何识别它


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

如果我们使用,
NSDate*currentDateAndTime=[NSDate-date],则根据设备仅返回UTC时间,而不是当前UTC时间

有什么简单的方法可以找到这个解决方案吗


任何帮助都将不胜感激。

使用:
NSDate*currentDateAndTime=[NSDate-date]


这将获得GMT参考区域中的绝对日期和时间。

使用此代码,它将帮助您

NSDate * datee = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];

NSLog(@"%@",localDateString);
试试这个:

斯威夫特:

let date = NSDate()
let dateFormatter = NSDateFormatter()
let timeZone = NSTimeZone(name: "UTC")

dateFormatter.timeZone = timeZone

println(dateFormatter.stringFromDate(date))
Obj-C:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];

[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:timeZone];       
NSLog(@"%@", [dateFormatter stringFromDate:date]);

这可能会解决你的问题

NSDate * date = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        NSString *currentTime = [dateFormatter stringFromDate:date];
        NSLog(@"current time is:%@",currentTime);

iOS中没有受信任的时间源。你只需要在单调和非单调的时间里操作

单调时间(或绝对时间)表示自过去某个任意固定点以来的绝对挂钟时间。
CACurrentMediaTime()
mach\u绝对时间
返回单调时间

非单调时间表示机器对当前挂钟的最佳猜测,即一天中的时间。当系统时钟改变时,它可以前后跳跃。
[NSDate]
调用返回它

作为一个选项,您可以从http
date
response头获取受信任的日期/时间。然后将其和当前单调时间(
CACurrentMediaTime()
)保存在钥匙链中。 以下是获取当前受信任时间的方法:

上次已知在线时间+(CACurrentMediaTime()-节省的单调时间)


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

您可以使用此代码获取当前时间:-

斯威夫特3
如果您在不使用任何时区的情况下手动设置时间,则它不起作用。它将在设备时间返回UTC时间。设备始终使用UTC时间工作。仅显示时间使用时区精度,但仅用于显示。我希望获得正确的当前时间。它将返回设备的当前时间,而不是当前UTC时间。如果不信任设备的时间,则需要web服务。。。。或NTP服务器,例如,请参阅以下答案:。
let date = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
formatter.dateFormat = "HH:MM a"
let currentTime: String = formatter.stringFromDate(date)
print("My Current Time is \(currentTime)")

Result **
Output : - "My Current Time is 11:05 AM\n"