Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get the timestamp from a Firebase realtime database key?

According to this blog post, firebase array keys are created using a timestamp:

It does this by assigning a permanent, unique id based on the current timestamp (offset to match server time).

Is there a way to recover this timestamp for use later, given the key?

like image 676
lowe0292 Avatar asked Jan 12 '15 18:01

lowe0292


1 Answers

As I said in my comment, you should not rely on decoding the timestamp from the generated id. Instead of that, you should simply store it in a property in your Firebase.

That said, it turns out to be fairly easy to get the timestamp back:

// DO NOT USE THIS CODE IN PRODUCTION AS IT DEPENDS ON AN INTERNAL 
// IMPLEMENTATION DETAIL OF FIREBASE
var PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
function decode(id) {
  id = id.substring(0,8);
  var timestamp = 0;
  for (var i=0; i < id.length; i++) {
    var c = id.charAt(i);
    timestamp = timestamp * 64 + PUSH_CHARS.indexOf(c);
  }
  return timestamp;
}
var key = prompt("Enter Firebase push ID");
if (key) {
  var timestamp = decode(key);
  console.log(timestamp+"\n"+new Date(timestamp));
  alert(timestamp+"\n"+new Date(timestamp));
}

I'll repeat my comment, just in case somebody thinks it is a good idea to use this code for anything else than as an exercise in reverse engineering:

Even if you know how to retrieve the timestamp from the key, it would be a bad idea to do this in production code. The timestamp is used to generate a unique, chronologically ordered sequence. If somebody at Firebase figures out a more efficient way (whichever subjective definition of efficiency they happen to choose) to accomplish the same goal, they might change the algorithm for push. If your code needs a timestamp, you should add the timestamp to your data; not depend on it being part of your key.

Update

Firebase documented the algorithm behind Firebase push IDs. But the above advice remains: don't use this as an alternative to storing the date.

like image 92
Frank van Puffelen Avatar answered Sep 25 '22 04:09

Frank van Puffelen