Skip to content

Commit a0820d5

Browse files
autopulatedmbroadst
authored andcommitted
fix(timestamp): getTimestamp support times beyond 2038
* Fix getTimestamp for times beyond 2038 Avoid treating timestamps with the most significant bit set as negative. The mongodb documentation describe the timetsamp portion of objectids as 'seconds since the unix epoch', so this seems to be the correct behaviour, although I cannot find a formal specification for it.however this is technically a breaking change if people were relying on timestamp values before 1970. * use readUInt32BE instead of bit twiddling * remove comment that no longer applies * add test case
1 parent ba98ccb commit a0820d5

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

Diff for: lib/objectid.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -249,7 +249,7 @@ class ObjectId {
249249
*/
250250
getTimestamp() {
251251
const timestamp = new Date();
252-
const time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
252+
const time = this.id.readUInt32BE(0);
253253
timestamp.setTime(Math.floor(time) * 1000);
254254
return timestamp;
255255
}

Diff for: test/node/object_id_tests.js

+5
Original file line numberDiff line numberDiff line change
@@ -99,4 +99,9 @@ describe('ObjectId', function() {
9999
expect(() => new ObjectId('abcdefghijkl').toHexString()).to.not.throw();
100100
expect(() => new ObjectId('abcdefŽhijkl').toHexString()).to.throw(TypeError);
101101
});
102+
103+
it('should correctly interpret timestamps beyond 2038', function() {
104+
var farFuture = new Date('2040-01-01T00:00:00.000Z').getTime();
105+
expect(new BSON.ObjectId(BSON.ObjectId.generate(farFuture/1000)).getTimestamp().getTime()).to.equal(farFuture);
106+
});
102107
});

0 commit comments

Comments
 (0)