Skip to content

Commit

Permalink
Merge pull request #10 from Liquidsoul/fix/iso8601-dates
Browse files Browse the repository at this point in the history
Workaround the unsupported milliseconds part of ISO8601DateFormatter
  • Loading branch information
Liquidsoul authored Jun 27, 2017
2 parents cbc0121 + aa3a09e commit 84c76f3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import Foundation
enum JSONDateFormatter {
static func date(from string: String) -> Date? {
if #available(iOS 10.0, macOS 10.12, *) {
return isoDateFormatter.date(from: string)
let dateString = string.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
return isoDateFormatter.date(from: dateString)
} else {
return dateFormatter.date(from: string)
}
Expand Down
7 changes: 6 additions & 1 deletion Templates/AutoJSONSerializable.stencil
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import Foundation
enum JSONDateFormatter {
static func date(from string: String) -> Date? {
if #available(iOS 10.0, macOS 10.12, *) {
return isoDateFormatter.date(from: string)
// [HACK] workaround for unsupported milliseconds part in ISO8601DateFormatter.
// "1985-04-12T23:20:50Z" is supported where "1985-04-12T23:20:50.678Z" is not.
// So this removes the ".678" part.
let dateString = string.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
// [/HACK]
return isoDateFormatter.date(from: dateString)
} else {
return dateFormatter.date(from: string)
}
Expand Down
22 changes: 22 additions & 0 deletions Tests/AutoJSONSerializationTests/JSONDateFormatterTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import XCTest
@testable import AutoJSONSerialization

class JSONDateFormatterTests: XCTestCase {
func test_dateFromString() {
let expectedDate = Date(timeIntervalSince1970: 482196050)

let dateStrings = [
"1985-04-12T23:20:50Z",
"1985-04-12T22:20:50-01:00",
"1985-04-12T23:20:50.678Z",
"1985-04-12T22:20:50.467-01:00"
]

dateStrings.forEach { dateString in
XCTAssertEqual(expectedDate,
JSONDateFormatter.date(from: dateString),
"Failed to correctly parse '\(dateString)'")
}
}

}
6 changes: 6 additions & 0 deletions Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,14 @@ extension AutoJSONSerializableTests {
("test_BasicTypesArrayPropertySerialization", test_BasicTypesArrayPropertySerialization),
]
}
extension JSONDateFormatterTests {
static var allTests = [
("test_dateFromString", test_dateFromString),
]
}

XCTMain([
testCase(AutoJSONDeserializableTests.allTests),
testCase(AutoJSONSerializableTests.allTests),
testCase(JSONDateFormatterTests.allTests),
])

0 comments on commit 84c76f3

Please sign in to comment.