将时间字符串转换为日期 swift

Convert time string into date swift

我正在使用 firebase 作为后端并像这样存储一串时间 7:00 下午。

我正在尝试转换从 Firebase 收到的字符串并将其转换为 NSDate,以便我可以对其进行排序、更改时间等

到目前为止,我已经在网上查看并得出了这段代码

dateFormatter.dateFormat = "hh:mm a"
                  dateFormatter.locale = NSLocale.current
                  dateFormatter.timeZone = NSTimeZone.local
                  let date = dateFormatter.date(from: item)
                  self.times.append(date!)
                  print("Start: \(date)")

其中项目是字符串 (7:00 PM)

当我 运行 应用程序时,控制台 returns:

Item: 9:00 AM

Start: Optional(2000-01-01 05:00:00 +0000)

我已经设置了时区、区域设置和格式。为什么返回的时间不正确?

打印出来的其他几个例子:

Item: 1:20 PM

Start: Optional(2000-01-01 17:20:00 +0000)

Item: 9:40 AM

Start: Optional(2000-01-01 05:40:00 +0000)

Item: 10:00 AM

Start: Optional(2000-01-01 05:00:00 +0000)

Item: 12:00 PM

Start: Optional(2000-01-01 17:00:00 +0000)

永远记住这一点:Date / NSDate 以 UTC 格式存储时间。如果您的时区不是 UTC,则 print(date) 返回的值将始终不同。

您可以通过指定 UTC 时区使其打印出存储在 Firebase 中的小时。默认为用户(即您的)时区:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let item = "7:00 PM"
let date = dateFormatter.date(from: item)
print("Start: \(date)") // Start: Optional(2000-01-01 19:00:00 +0000)