我使用 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)")
其中 item 是字符串 (7:00 PM)
当我运行应用程序时,控制台返回:
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)
关于swift - 将时间字符串快速转换为日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333223/