[英]DateFormatter wrong time output when a different month is selected
我的應用程序中有一個單獨的 DatePicker 和 TimePicker 組件。
一旦用戶選擇了所需的日期和時間,我將構造一個新的Date
object,如下所示:
let timeStamp = Date(year: selectedDate.year, month: selectedDate.month, day: selectedDate.day, hour: selectedTime.hour, minute: selectedTime.minute)
然后我使用DateFormatter
到 output 用戶選擇的確切時間如下:
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.string(from: timeStamp)
現在我有一個非常奇怪的錯誤,有時時間 output 是正確的(時間將以 UTC+2 顯示),有時它會不正確(時間將以 UTC+1 顯示),我完全不知道會是什么造成這種情況。
示例 1(正確輸出):
User selects: May 26, 2020 - 18:38
Date ISO output: "2020-05-26T16:38:00Z"
DateFormatter output: "18:38"
This is the correct output
示例 2(錯誤輸出):
User selects: March 26, 2020 - 18:38
Date ISO output: "2020-03-26T16:38:00Z"
DateFormatter output: "17:38"
This is not the correct output. Time should be 18:38 like in the above example.
有人請告訴我這怎么可能? 從字面上看,唯一的區別是用戶選擇了 3 月而不是 5 月(不同的月份),並且由於某種原因混淆了 DateFormatter,因此時間 output 位於不同的時區。
我正在使用 SwiftDate 來處理一般的日期。
這可能是因為 5 月夏令時生效,與 UTC 的差異從 +1 變為 +2 小時
您可以使用當前的 TimeZone 並使用它添加配置您的 DateFormatter
let timezone = TimeZone.current
dateFormatter.timeZone = timezone
這應該確保您始終使用您的設備當前使用的相同時區
設置正確formatter.locale
,您可以嘗試Locale(identifier: "en_US_POSIX")
或嘗試使用formatter.timeZone
屬性。 也許TimeZone.current
或TimeZone(secondsFromGMT: 0)
會解決你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.