How am I going to convert an id with a date and timestamp into an ObjectId using kotlin?

117 Views Asked by At
"id": {
  "date": "Wed Aug 16 18:51:43 PST 2023",
  "timestamp": 1692183103
}

I need to convert this id into an ObjectId, "64dcaa3fcac7f22c65bf21e8".

Here is my code:

val inputDate = id.getString("date")
val timestamp = id.getLong("timestamp")

val dateFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH)
val date = dateFormat.parse(inputDate)
val time = date.time / 1000L
val timeHex = timestamp.toString(16).padStart(8, '0')

return timeHex.substring(8) + timeHex.substring(0, 2) + timeHex.substring(2, 8)

however it is returning only "64dcaa3f"

What should I do?

1

There are 1 best solutions below

0
BerkanAcikgoz On

I think this code will work for you.

val inputDate = id.getString("date")
val timestamp = id.getLong("timestamp")

val dateFormat = SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH)
val date = dateFormat.parse(inputDate)
val time = date.time / 1000L
val timeHex = timestamp.toString(16).padStart(8, '0')

val objectId = timeHex.substring(0, 4) + timeHex.substring(8) + timeHex.substring(2, 8)

return objectId

This code get this output: 64dcaa3fcac7f22c65bf21e8