Skip to content

Commit

Permalink
fix(timestamp): getTimestamp support times beyond 2038
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
autopulated authored and mbroadst committed Feb 19, 2019
1 parent ba98ccb commit a0820d5
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/objectid.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ class ObjectId {
*/
getTimestamp() {
const timestamp = new Date();
const time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24);
const time = this.id.readUInt32BE(0);
timestamp.setTime(Math.floor(time) * 1000);
return timestamp;
}
Expand Down
5 changes: 5 additions & 0 deletions test/node/object_id_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,9 @@ describe('ObjectId', function() {
expect(() => new ObjectId('abcdefghijkl').toHexString()).to.not.throw();
expect(() => new ObjectId('abcdefŽhijkl').toHexString()).to.throw(TypeError);
});

it('should correctly interpret timestamps beyond 2038', function() {
var farFuture = new Date('2040-01-01T00:00:00.000Z').getTime();
expect(new BSON.ObjectId(BSON.ObjectId.generate(farFuture/1000)).getTimestamp().getTime()).to.equal(farFuture);
});
});

0 comments on commit a0820d5

Please sign in to comment.