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

标签 swift nsdate

我使用 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/

相关文章:

ios - ScrollView 内的 LazyVStack 中具有可变高度的内容导致口吃/跳跃

ios - 如何获取当月的开始日期和结束日期(Swift 3)

ios - 核心数据 : filtering entries based on time component of NSDate

arrays - 如果 var 似乎在 Swift 中深度复制数组。如果让?

ios - Firebase 多个观察者复制单元格

swift - 计算两个日期之间的差异。 swift 1.2

ios - 检查系统时间是自动的还是用户设置的

iphone - NSDate 时间或 !time 其中

xcode - SplitViewController设置为窗口内容导致Window不出现

ios - XCode 导出应用程序,通配符错误