Skip to content

Commit a1a668f

Browse files
committed
Add getSmallestWithDate factory method to ObjectId
JAVA-3683
1 parent eac754d commit a1a668f

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

bson/src/main/org/bson/types/ObjectId.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,21 @@ public static ObjectId get() {
7474
return new ObjectId();
7575
}
7676

77+
/**
78+
* Gets a new object id with the give date value and all other bits zeroed.
79+
* <p>
80+
* The returned object id will compare as less than or equal to any other object id within the same second as the given date, and
81+
* less than any later date.
82+
* </p>
83+
*
84+
* @param date the date
85+
* @return the ObjectId
86+
* @since 4.1
87+
*/
88+
public static ObjectId getSmallestWithDate(final Date date) {
89+
return new ObjectId(dateToTimestampSeconds(date), 0, (short) 0, 0, false);
90+
}
91+
7792
/**
7893
* Checks if a string could be an {@code ObjectId}.
7994
*

bson/src/test/unit/org/bson/types/ObjectIdTest.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,16 @@ public void testBytesRoundtrip() {
9191
assertEquals("41d91c58988b09375cc1fe9f", expected.toString());
9292
}
9393

94+
@Test
95+
public void testGetSmallestWithDate() {
96+
Date date = new Date(1588467737760L);
97+
byte[] expectedBytes = new byte[]{94, -82, 24, 25, 0, 0, 0, 0, 0, 0, 0, 0};
98+
ObjectId objectId = ObjectId.getSmallestWithDate(date);
99+
assertArrayEquals(expectedBytes, objectId.toByteArray());
100+
assertEquals(date.getTime() / 1000 * 1000, objectId.getDate().getTime());
101+
assertEquals(-1, objectId.compareTo(new ObjectId(date)));
102+
}
103+
94104
@Test
95105
public void testGetTimeZero() {
96106
assertEquals(0L, new ObjectId(0, 0).getDate().getTime());

0 commit comments

Comments
 (0)