【问题标题】:Swift: Create a Date() from a Google Drive API TimestampSwift:从 Google Drive API 时间戳创建 Date()
【发布时间】:2021-07-20 12:39:18
【问题描述】:

我正在使用 Swift 中的 Google Drive API,我正在使用的数据之一是时间戳,格式如下:2021-04-18T22:50:33.235Z

我的 Date 对象不断收到 nil,我认为它与我的 DateFormatter() 有关,但我似乎无法弄清楚到底出了什么问题。

这是我尝试过的代码:

var creationDateAsString = "2021-04-18T22:50:33.235Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.date(from: creationDateAsString) {
   //do what I need to do
}

感谢您提供的任何帮助。

【问题讨论】:

  • 我没有发现问题,在我的操场上(Swift 5.1)它可以工作。
  • 它对我来说也很好,注意你也可以在这里使用 ISO8601DateFormatter,通过将格式选项设置为dateFormatter.formatOptions = [.withInternetDateTime,.withFractionalSeconds]
  • 您的设备是否显示 12h 格式?可能是罪魁祸首。

标签: ios swift date timestamp dateformatter


【解决方案1】:

确实,出于某种原因,这段代码可以在操场上运行,但不能在我的实际 Swift 应用程序中运行。但是,我能够通过定义语言环境来解决这个问题:

var creationDateAsString = "2021-04-18T22:50:33.235Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
if let date = dateFormatter.date(from: creationDateAsString) {
    //do what I need to do
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2012-12-16
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多