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「歐洲/倫敦」
您不在'components'中指定'TimeZone',所以日曆的設置被用作默認設置。另外,'NSTimeZone(名稱:「GMT」)!因爲TimeZone'沒有任何意義,只需使用'TimeZone(縮寫:「GMT」)' –
David,謝謝。但是timeZone已經由dateComponents函數指定。它實際上不是零。它與NSTimeZone \t「歐洲/倫敦」相等。所以我仍然不清楚是什麼問題... – andrii
你原來的代碼工作得很好。你唯一的困惑是解釋日誌記錄對象的輸出。順便說一句 - 你沒有時間創造一個約會。您正在創建一個設置爲當地時間午夜的日期(在您的第一組代碼中)。或GMT時間格林尼治標準時間午夜時間。 – rmaddy