2016-05-30 78 views
0

我知道這是重複的問題。我已經回顧了很多答案,但仍然沒有得到任何解決方案。我的問題是, 如果用戶手動設置它,我怎樣才能得到設備的時間?如何在iOS中獲得正確的當前時間?

我已經實現了一個聊天應用程序。但在這個應用程序中,我有時間問題。如果用戶設置了手動時間,那麼我們如何識別它。

我想獲得正確的當前UTC時間。所以使用這個,我可以識別設備時間和UTC時間之間的差異。

如果我們使用的是NSDate *currentDateAndTime = [NSDate date];,那麼它只根據設備返回UTC時間,而不是當前UTC時間。

有沒有什麼簡單的方法可以找到這個解決方案?

任何幫助,將不勝感激。

+0

需要使用Web服務,如果你不信任設備的時間。 – Desdenova

+1

...或NTP服務器,參見例如這個答案:http://stackoverflow.com/questions/14964318/how-can-i-get-the-actual-date-and-time-if-the-device-date-and-time-are-inaccurat。 –

回答

0

用途:NSDate *currentDateAndTime = [NSDate date];

這將讓你在GMT參考區的絕對日期和時間。

+1

如果您在不使用任何時區的情況下手動設置時間,則它不起作用。它將在UTC時間返回設備時間。 –

+0

設備始終使用UTC時間。只顯示時間使用timeZone精度,但僅用於顯示。 –

0

使用此代碼它可以幫助你

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); 
+2

我想獲得正確的當前時間。它將返回設備的當前時間,而不是當前UTC時間。 –

0

試試這個:

迅速:

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]); 
1

這可能會解決你的問題

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

在iOS中沒有可信的時間源。你只需要操作單調和非單調的時間。

單調時間(或絕對時間)表示過去某些任意固定點以來絕對過去的掛鐘時間。 CACurrentMediaTime()mach_absolute_time返回單調時間。

非單調時間表示機器對當前掛鐘時間的當前時間的最佳猜測。隨着系統時鐘的更改,它可以前後跳轉。 [NSDate date]調用返回它。

作爲選項,您可以從http Date響應標題中獲取可信日期/時間。然後將它和當前單調時間(CACurrentMediaTime())保存在鑰匙串中。 這裏是獲取當前的可信時間的方式:

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

另一種解決方案是使用NTP服務器。

-1

您可以使用此代碼獲取當前時間: -

斯威夫特3

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" 
相關問題