Skip to content

Commit 4437d9f

Browse files
authored
SWIFT-893 Expose timestamp property on BSONObjectID
1 parent 4159d68 commit 4437d9f

File tree

2 files changed

+20
-14
lines changed

2 files changed

+20
-14
lines changed

Sources/BSON/BSONObjectID.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,15 @@ public struct BSONObjectID: Equatable, Hashable, CustomStringConvertible {
1111

1212
public var description: String { self.hex }
1313

14+
/// The timestamp portion of this `BSONObjectID` represented as a `Date`.
15+
public var timestamp: Date {
16+
var value = Int()
17+
_ = withUnsafeMutableBytes(of: &value) {
18+
self.oid[0..<4].reversed().copyBytes(to: $0)
19+
}
20+
return Date(timeIntervalSince1970: TimeInterval(value))
21+
}
22+
1423
/// ObjectID Bytes
1524
internal let oid: [UInt8]
1625

Tests/BSONTests/BSONObjectIDTests.swift

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,6 @@ import Foundation
33
import Nimble
44

55
extension BSONObjectID {
6-
// timestamp
7-
internal var timestamp: Int {
8-
var value = Int()
9-
_ = withUnsafeMutableBytes(of: &value) { self.oid[0..<4].reversed().copyBytes(to: $0) }
10-
return value
11-
}
12-
136
// random value
147
internal var randomValue: Int {
158
var value = Int()
@@ -47,8 +40,14 @@ final class BSONObjectIDTests: BSONTestCase {
4740
}
4841

4942
func testFieldAccessors() throws {
50-
let oid = try BSONObjectID("FEEEEEEEFBBBBBBBBBFAAAAA")
51-
expect(oid.timestamp).to(equal(0xFEEE_EEEE))
43+
let format = DateFormatter()
44+
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
45+
format.timeZone = TimeZone(secondsFromGMT: 0)
46+
let timestamp = format.date(from: "2020-07-09 16:22:52")
47+
// 5F07445 is the hex string for the above date
48+
let oid = try BSONObjectID("5F07445CFBBBBBBBBBFAAAAA")
49+
50+
expect(oid.timestamp).to(equal(timestamp))
5251
expect(oid.randomValue).to(equal(0xFB_BBBB_BBBB))
5352
expect(oid.counter).to(equal(0xFAAAAA))
5453
}
@@ -62,13 +61,11 @@ final class BSONObjectIDTests: BSONTestCase {
6261
}
6362

6463
func testTimestampCreation() throws {
65-
let id = BSONObjectID()
66-
let dateFromID = Date(timeIntervalSince1970: TimeInterval(id.timestamp))
64+
let oid = BSONObjectID()
65+
let dateFromID = oid.timestamp
6766
let date = Date()
68-
6967
let format = DateFormatter()
70-
// should be ok to say the timestamps are within the same second but just to be safe, omit seconds
71-
format.dateFormat = "yyyy-MM-dd HH:mm"
68+
format.dateFormat = "yyyy-MM-dd HH:mm:ss"
7269

7370
expect(format.string(from: dateFromID)).to(equal(format.string(from: date)))
7471
}

0 commit comments

Comments
 (0)