2017-09-16 43 views
0

我想獲得沒有時間的今天的日期,所以我可以用它來比較我從API獲得的其他Date對象。使用Calendar.date時區是錯誤的

這裏是我的代碼:

var today = Date() 
let gregorian = Calendar(identifier: .gregorian) 
var components = gregorian.dateComponents([.timeZone, .year, .month, .day, .hour, .minute,.second], from: today) 

components.hour = 0 
components.minute = 0 
components.second = 0 

today = gregorian.date(from: components)! 

但是我有一個時區的一個奇怪的問題。今天是例如16/09/17,但在今天結束就等於

2017年9月15日23:00:00 UTC

解決它的唯一途徑實際上是將我的時區指定爲GMT。

components.timeZone = NSTimeZone(name: "GMT")! as TimeZone 

然後結果是正確的。

2017年9月16日00:00:00 UTC

爲什麼你需要指定的時區,因爲它已經應由dateComponents或我在做什麼錯成立。
之前設定我自己的時區是等於NSTimeZone「歐洲/倫敦」

+0

您不在'components'中指定'TimeZone',所以日曆的設置被用作默認設置。另外,'NSTimeZone(名稱:「GMT」)!因爲TimeZone'沒有任何意義,只需使用'TimeZone(縮寫:「GMT」)' –

+0

David,謝謝。但是timeZone已經由dateComponents函數指定。它實際上不是零。它與NSTimeZone \t「歐洲/倫敦」相等。所以我仍然不清楚是什麼問題... – andrii

+1

你原來的代碼工作得很好。你唯一的困惑是解釋日誌記錄對象的輸出。順便說一句 - 你沒有時間創造一個約會。您正在創建一個設置爲當地時間午夜的日期(在您的第一組代碼中)。或GMT時間格林尼治標準時間午夜時間。 – rmaddy

回答

0

時區「歐洲/倫敦」對應於「BST」的時刻,這是英國夏令時間,這是GMT + 1,因此你看到的問題。

當使用DateFormatter並將其設置爲.full時,您可以看到此內容。

let df = DateFormatter() 
df.timeZone = TimeZone(identifier: "Europe/London") 
df.dateStyle = .medium 
df.timeStyle = .full 
print(df.string(from: Date())) // "Sep 16, 2017, 4:56:55 PM British Summer Time" 
df.timeZone = TimeZone.current //I am actually in London, so this will be the same as explicitly setting it to Europe/London 
print(df.string(from: Date())) // "Sep 16, 2017, 4:56:55 PM British Summer Time" 
df.timeZone = TimeZone(abbreviation: "UTC") 
print(df.string(from: Date())) // "Sep 16, 2017, 3:56:55 PM GMT"