Skip to content

Commit

Permalink
Allow Date to be decoded from a Double
Browse files Browse the repository at this point in the history
  • Loading branch information
Joannis committed Feb 26, 2023
1 parent ff36ca6 commit c299369
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
8 changes: 5 additions & 3 deletions Sources/BSON/Types/Primitives.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
14 changes: 14 additions & 0 deletions Tests/BSONTests/BSONEncoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit c299369

Please sign in to comment.