Swift和iso8601尝试解析“ HH:mm:ss”

时间:2018-09-28 11:51:10

标签: swift

我们使用了Decodable,并且有一个时间:Date字段,但是来自服务器的时间只有“ HH:mm:ss”格式。带有DateInRegion的另一个日期解析器。

但是此字段崩溃应用 我尝试在解码器中执行smth,但看不到任何属性(.count) 而且我现在不需要做什么

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ decoder -> Date in
  do {
    let value = try decoder.singleValueContainer()
    let string = try value.decode(String.self)
    if string.conut == 8 {
        if let date = DateInRegion(
            string: string,
            format: .iso8601(options: .withTime),
            fromRegion: Region.Local()
            ) {
            return date.absoluteDate
        } else {
            throw DecodingError.nil
        }
    } else if let date = DateInRegion(
      string: string,
      format: .iso8601(options: .withInternetDateTime),
      fromRegion: Region.Local()
      ) {
      return date.absoluteDate
    } else {
      throw DecodingError.nil
    }
  } catch let error {

1 个答案:

答案 0 :(得分:0)

不确定要实现的目标,但似乎您想在单个JSON解码器中处理多种日期格式。

鉴于响应结构为Decodable

struct Response: Decodable {
  var time: Date
  var time2: Date
}

您可以将解码器配置为处理所需的所有日期格式:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
  // Extract string date from the container
  let container = try decoder.singleValueContainer()
  let stringDate = try container.decode(String.self)

  // Trying to parse the "HH:mm:ss" format
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "HH:mm:ss"
  if let date = dateFormatter.date(from: stringDate) {
    return date // successfully parsed "HH:mm:ss" format
  }

  // Trying to parse the iso8601 format
  if let date = ISO8601DateFormatter().date(from: stringDate) {
    return date // successfully parsed iso8601 format.
  }

  // Unknown date format, throw an error.
  let context = DecodingError.Context(codingPath: [], debugDescription: "Unable to parse a date from '\(stringDate)'")
  throw DecodingError.dataCorrupted(context)
})

注意:这是一个示例代码,它并不是非常优化(每次您想解析日期时,DateFormatter都会初始化,使用蛮力解析来确定日期是否在是否使用“ HH:mm:ss”格式,...)。

我认为,对此进行优化的最佳方法是使用多个解码器,每个解码器均配置为特定的日期格式,并在需要时使用正确的解码器。例如,如果您尝试从API解析JSON,则应该能够确定是否需要解析iso8601格式或其他格式,并相应地使用正确的解码器。

以下是解码器在操场上工作的示例:

let json = """
{"time": "11:05:45", "time2": "2018-09-28T16:02:55+00:00"}
"""

let response = try! decoder.decode(Response.self, from: json.data(using: .utf8)!)
response.time // Jan 1, 2000 at 11:05 AM
response.time2 // Sep 28, 2018 at 6:02 PM