【问题标题】:unable to create date from format "yyyy-MM-dd'T'HH:mm:ss+00:00"无法从格式“yyyy-MM-dd'T'HH:mm:ss+00:00”创建日期
【发布时间】:2018-07-01 22:25:14
【问题描述】:

我想从字符串转换为日期。 我在这里使用 "yyyy-MM-dd'T'HH:mm:ss+00:00" 的格式是否正确?

extension String {
    func format(_ format:String) -> String {
        var date: Date?
        let dateFormatterGet = DateFormatter()
        let dateFormatterOutput = DateFormatter()
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"
        dateFormatterOutput.dateFormat = format
        if let d = dateFormatterGet.date(from: self) {
            date = d
        }
        return dateFormatterOutput.string(from: date!)
    }
}

extension Date {
    func string(with format: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: self)
    }
}

【问题讨论】:

  • Annnndddd,你输入了什么?你有什么问题?
  • 为什么在日期格式中使用 +00:00?

标签: swift dateformatter


【解决方案1】:

问题出在一行:

dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+00:00"

+00:00需要替换成xxxx如:

dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx"

您的代码将变为:

func format(_ format:String) -> String {
    var date: Date?
    let dateFormatterGet = DateFormatter()
    let dateFormatterOutput = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxxx"
    dateFormatterOutput.dateFormat = format
    if let d = dateFormatterGet.date(from: self) {
        date = d
    }
    return dateFormatterOutput.string(from: date!)
}

注意:这里我假设您使用的日期字符串将包含时区为 +xx:xx(例如 +02:00) 等等在。但是,对于不同的格式,您需要使用不同数量的x(如果时区不包含Z,则使用小x):

  1. x -> -08, +0330
  2. xx -> -0800
  3. xxx -> -800, -075254
  4. xxxx -> -8:00, -07:52:54

如果时区包含Z,那么我们使用大写X

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 2014-12-02
    • 2018-11-28
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 2019-08-25
    相关资源
    最近更新 更多