swift - String 到 Date 的时间转换 : 12 is becoming 00 swift

标签 swift time time-format

我正在将时间保存到 Firebase,然后允许用户重新加载保存的时间。

当我从服务器提取数据(作为字符串)然后将时间转换回日期类型时,它从 12:00(中午)变为 00:00(午夜)。

我可以在我的 Firebase 实时数据库上看到数据,它清楚地显示 12:00 而不是午夜。

Firebase Image

这是我用来从我从实时数据库下载的字典中提取数据的代码。

if let gtt1hourLabTime = patientDataDictionary["1 Hour lab Time"] as? String {
      if let realgtt1HourLabTime = timeFormatTool(gtt1hourLabTime) {
                print(realgtt1HourLabTime)
                patientVC.gtt1HourLabTime = realgtt1HourLabTime
       }
}

这是我的时间格式工具:

func timeFormatTool(_ dateStr: String) -> Date? {
        let simpleDateFormat = DateFormatter()
        simpleDateFormat.dateFormat = "hh:mm"

        let date = simpleDateFormat.date(from: dateStr)
        return date
}

打印出来的时间是这样的:

2000-01-01 00:18:00 +0000

最佳答案

因为您使用的格式是 hh:mm,所以在 11:59 之后格式返回到 00:00。如果你想要 24 小时格式,其中包括 12:xx,你只需要将你的日期格式更改为:

simpleDateFormat.dateFormat = "HH:mm"

关于swift - String 到 Date 的时间转换 : 12 is becoming 00 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46811799/

相关文章:

c++ - 在 localtime() 中崩溃,但 gmtime() 有效

datetime - 什么是 TAI64 时间格式?

xcode - 在 Swift 中将图像从 .write 恢复到文件

ios - 在动态 Swift 框架(带/不带 Cocoapods)中导入 Firebase 并将框架导入应用程序目标

java - 如何从日期/时间选择器对话框获取日期和时间并显示它?

ios - 在 Swift 中准确测量时间以进行跨设备比较

angular - Angular 6 的时间格式

iphone - 根据不在设备设置上的应用程序设置,在 UIDatepicker 中以 12 和 24 小时格式显示时间

ios - 在 iOS 的 ViewController 中声明 View 时,为什么在 Swift 中使用 "weak"关键字

ios - 在 CGRectMake、Swift、UIkit 中使用变量