Swift 时间总是比实际时间晚 3 小时

Swift Time always late by 3 hours from real time

我有一个包含一组小时时间字符串的数组,当我想将它更改为日期时,我得到的时间比实际时间晚了 3 小时。

我的日期格式化程序如下所示

 let formatter = DateFormatter()
        formatter.dateFormat = "h:mm a"
        formatter.timeStyle = .short
        formatter.dateStyle = .none
 startArr = ["5:14 Am","1:07 PM" , "4:41 PM", "7:28 PM", "8:52 PM"]
            let startdateArray = (startArr).map { Calendar.current.dateComponents([.hour, .minute], from:formatter.date(from:[=12=])!) }
            let upcomingDates = startdateArray.map { Calendar.current.nextDate(after: Date(), matching: [=12=], matchingPolicy: .nextTime)!  }

            let nextDate = upcomingDates.sorted().first!
            print("next date", nextDate)
            for (i, n) in startArr.enumerated() {
                print(i, "->", n)
            }

我从上面的代码片段中得到了以下输出

下一个日期 2019-09-10 13:41:00 +0000

0 -> 5:14 AM

1 -> 1:07 PM

2 -> 4:41 PM

3 -> 7:28 PM

4 -> 8:52 PM

DateFormattertimeZone设为TimeZone(abbreviation: "GMT"),即

let startArr = ["5:14 AM", "1:07 PM", "4:41 PM", "7:28 PM", "8:52 PM"]
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
formatter.timeZone = TimeZone(abbreviation: "GMT")
let datesArray = startArr.compactMap({ formatter.date(from: [=10=]) })
print(datesArray)

我已经通过为打印制作另一个格式化程序解决了这个问题

        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm a"
        formatter.timeZone = TimeZone(identifier: localTimeZoneName)

和打印格式化程序

        let printf = DateFormatter()
        printf.dateFormat = "yyyy-mm-dd hh:mm:ss"
        printf.timeZone = TimeZone(identifier: localTimeZoneName)

然后我在使用 printf 格式化程序

将其转换为字符串后打印了 nextDate
     print("next date", printf.string(from: nextDate))