Can You Get The Timestamp From A Firebase Realtime Database Key?


Answer :

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.


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable