Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active September 22, 2017 12:47
Show Gist options
  • Save dimpiax/3b6317cc86dbee05abd6563de2a2a581 to your computer and use it in GitHub Desktop.
Save dimpiax/3b6317cc86dbee05abd6563de2a2a581 to your computer and use it in GitHub Desktop.

Revisions

  1. dimpiax revised this gist Sep 22, 2017. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions iso8601.swift
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    let decode = JSONDecoder()
    decode.dateDecodingStrategy = .custom { decoder -> Date in
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .custom { decoder -> Date in
    let valueContainer = try decoder.singleValueContainer()
    let value = try valueContainer.decode(String.self)

  2. dimpiax created this gist Sep 22, 2017.
    18 changes: 18 additions & 0 deletions iso8601.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    let decode = JSONDecoder()
    decode.dateDecodingStrategy = .custom { decoder -> Date in
    let valueContainer = try decoder.singleValueContainer()
    let value = try valueContainer.decode(String.self)

    if let regex = try? NSRegularExpression(pattern: "\\.\\d+", options: []) {
    let result = regex.stringByReplacingMatches(in: value, options: [], range: NSRange(location: 0, length: value.count), withTemplate: "")

    if let date = ISO8601DateFormatter().date(from: result) {
    return date
    }
    }

    let context = DecodingError.Context(codingPath: valueContainer.codingPath, debugDescription: "Invalid date")
    throw DecodingError.dataCorrupted(context)
    }

    // decodes 1970-01-01T00:00:00.111Z as 1970-01-01T00:00:00Z