【问题标题】:Wrong date in swift 5 after conversion [duplicate]转换后swift 5中的日期错误[重复]
【发布时间】:2020-05-23 06:06:49
【问题描述】:

我正在将当前日期转换为 GMT/UTC 日期字符串。但是每次它返回给我的日期都是错误的。

我今天的日期是07 February 2020, 11:09:20 AM。您可以参考下图。

这是我的代码:

let apiFormatter = DateFormatter()
//apiFormatter.dateStyle = DateFormatter.Style.long
//apiFormatter.timeStyle = DateFormatter.Style.long
//apiFormatter.calendar = Calendar.current
apiFormatter.timeZone = TimeZone.init(identifier: "GMT") //TimeZone(abbreviation: "UTC") //TimeZone.current //
//apiFormatter.locale = Locale.current
//apiFormatter.dateFormat = "yyyy-MM-DD HH:mm:ss"
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
//apiFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ssZ"
let endDate = apiFormatter.string(from: Date())
print(endDate)

我得到的回报是您也可以查看图片 - 2020-02-38T05:33:34.598Z。我已经尝试了所有格式,但没有任何运气。谁能指出哪里出了问题?

【问题讨论】:

  • 你期望得到什么?
  • 2020-02-07T05:33:34.598 +0530 这就是我想要的。
  • 其实,没有。 2020-02-07T05:33:34.598 +0530 与“现在”相去甚远。 5个半小时过去了。 2020-02-38T05:33:34.598Z 代表“现在”附近的某个地方,2020-02-07T12:23:25.175 +0530 也是如此。你确定你还想要2020-02-07T05:33:34.598 +0530吗?
  • 您显示的内容 (38) 是您注释掉的 DD(大写,一年中的一天)的结果。
  • 另外,您必须将语言环境设置为en_US_POSIX

标签: ios swift date ios13


【解决方案1】:

首先格式应该是:

apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Z 不是文字字母,它是对时区的描述。但是,将其设为文字可能不会造成问题。

您输出中的38 显然是由您注释掉的DD 格式引起的。

不过,您必须设置语言环境:

apiFormatter.locale = Locale(identifier: "en_US_POSIX")

否则12/24小时切换会有问题。

let apiFormatter = DateFormatter()
apiFormatter.locale = Locale(identifier: "en_US_POSIX")
// remove this if you want to keep your current timezone (shouldn't really matter, the time is the same)
apiFormatter.timeZone = TimeZone(secondsFromGMT: 0)
apiFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

let endDate = apiFormatter.string(from: Date())
print(endDate) // 2020-02-07T08:25:23.470+0000
print(Date())  // 2020-02-07 08:25:23 +0000

另请注意,您可以使用ISO8601DateFormatter 代替DateFormatter

【讨论】:

    【解决方案2】:

    试试这个并根据你从服务器获取的格式进行调整 -

    private func getFormatedDateInString(_ dateString: String) -> String? {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        dateFormatter.timeZone = TimeZone(identifier: "UTC")
        if let date = dateFormatter.date(from: dateString) {
            dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            dateFormatter.timeZone = TimeZone.current
            let timeStamp = dateFormatter.string(from: date)
            return timeStamp
        }
        return nil
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-21
      • 1970-01-01
      • 2021-06-23
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 2018-01-02
      相关资源
      最近更新 更多