Converting MongoDB ObjectId to Timestamp

How would I go about converting a MongoDB ObjectId into a timestamp? I want to sort objects that have an objectid in chronological order, but need to somehow do this in lua? This is how it is done in JavaScript:

var dateFromObjectId = function (objectId) {
  return new Date(parseInt(objectId.substring(0, 8), 16) * 1000)                
};

Most of it is quite easy to figure out, but I’m not sure what the equivalent or how to make “parseInt” in lua?

The equivalent script would probably look close to this:

--returns just a number really
local function dateFromObjectId(objectId)
	return tonumber(objectId:sub(1, 8), 16) * 1000
end)

You probably wouldn’t be able to sort by date objects, but you could probably just sort it by the number returned by the objectId instead:

local data = {
	{Data = {}, Tick = dateFromObjectId(objectId)}
}

table.sort(data, function(a, b) a.Tick < b.Tick end)

I never knew lua could process hexadecimals using tonumber until now

Thanks, I didn’t know that either! Guess we both learned something today.

1 Like