diff --git a/Sources/BSON/Types/Primitives.swift b/Sources/BSON/Types/Primitives.swift index a0c3a7b..c93f1a2 100644 --- a/Sources/BSON/Types/Primitives.swift +++ b/Sources/BSON/Types/Primitives.swift @@ -157,11 +157,13 @@ fileprivate struct CustomKey: CodingKey { extension Date: BSONDataType { init(primitive: Primitive?) throws { - guard let value = primitive as? Date else { + if let value = primitive as? Date { + self = value + } else if let value = primitive as? Double { + self = Date(timeIntervalSince1970: value) + } else { throw BSONTypeConversionError(from: type(of: primitive), to: Date.self) } - - self = value } } diff --git a/Tests/BSONTests/BSONEncoderTests.swift b/Tests/BSONTests/BSONEncoderTests.swift index aece39f..5d63f20 100644 --- a/Tests/BSONTests/BSONEncoderTests.swift +++ b/Tests/BSONTests/BSONEncoderTests.swift @@ -85,6 +85,20 @@ class BSONEncoderTests: XCTestCase { let codedDocument = try BSONEncoder().encode(floatArray) XCTAssertEqual(codedDocument["0"] as? Double, 4) } + + func testDecodeDateFromDouble() throws { + let date = Date() + let document: Document = [ + "date": date.timeIntervalSince1970 + ] + + struct DateContainer: Codable { + let date: Date + } + + let container = try BSONDecoder().decode(DateContainer.self, from: document) + XCTAssertEqual(date, container.date) + } @available(OSX 10.12, *) func testEncoding() throws {