日期格式化程序选择其他月份时输出错误的时间



我的应用程序中有一个单独的DatePicker和TimePicker组件。

用户选择所需的日期和时间后,我构造一个新的Date对象,如下所示:

let timeStamp = Date(year: selectedDate.year, month: selectedDate.month, day: selectedDate.day, hour: selectedTime.hour, minute: selectedTime.minute)

然后,我使用DateFormatter输出用户选择的确切时间,如下所示:

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
formatter.string(from: timeStamp)

现在我有一个非常奇怪的错误,有时时间输出是正确的(时间将以 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.

有人请告诉我这怎么可能?从字面上看,唯一的区别是用户选择三月而不是五月(不同的月份(,并且由于某种原因混淆了日期格式化程序,因此时间输出位于不同的时区。

我正在使用SwiftDate来处理一般的日期。

设置正确的formatter.locale,您可以尝试Locale(identifier: "en_US_POSIX")或尝试使用formatter.timeZone属性。也许TimeZone.currentTimeZone(secondsFromGMT: 0)可以解决您的问题

这可能是因为在 5 月夏令时生效,并且与 UTC 的差异从 +1 小时变为 +2 小时

您可以使用当前时区并添加配置日期格式化程序

let timezone = TimeZone.current
dateFormatter.timeZone = timezone

这应该确保您始终使用设备当前使用的相同时区

最新更新