Java ObjectId 2038

On java driver, Bson have type ObjectId.

ObjectId objId = new ObjectId(Integer.MAX_VALUE , 100);
System.out.println(objId.getDate());
it will output
Tue Jan 19 12:14:07 JST 2038

so java driver has a 2038 problerm ?

Hi @bato_bolg welcome to the community!

so java driver has a 2038 problerm ?

It’s not really a Java driver thing, since the timestamp was encoded as part of ObjectID which is the standard default primary key assigned to your document if you don’t specify the _id field.

However please note that although the ObjectId contains a 32-bit timestamp (which will overflow in 2038), the main purpose of ObjectId is to provide a unique value for the _id field, that can be reasonably unique and easy to generate. Yes you can extract the timestamp from it, but that’s not its main purpose. In fact, overflowing timestamp in the ObjectId would likely still fulfill the main role of ObjectId of providing you with a reasonably unique value to serve as _id.

If you need to have a timestamp for document insertion, it’s best to have a specific field dedicated to it in the document instead of relying on the ObjectId timestamp.

Best regards
Kevin

Thank you, I test alter that and got the even after 2038 ObjectId still works no problem.

SimpleDateFormat formatter = new SimpleDateFormat(“dd-MMM-yyyy”, Locale.ENGLISH );

String dateInString = “7-FEB-2106”;

Date date = formatter.parse(dateInString);
int ttt = ( int ) (date.getTime() / 1000);

System.out.println(ttt);

ObjectId objId = new ObjectId(ttt, 100);

System.out.println(objId.getDate());
System.out.println(objId.toString());

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.