您可以从Firebase实时数据库密钥获取时间戳吗? [英] Can you get the timestamp from a Firebase realtime database key?

查看:63
本文介绍了您可以从Firebase实时数据库密钥获取时间戳吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此博客文章,使用时间戳创建firebase数组键:

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

这是通过基于当前时间戳(与服务器时间匹配的偏移量)分配一个永久的唯一ID来实现的.

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?

推荐答案

正如我在评论中所说,您不应该依赖于从生成的id解码时间戳.取而代之的是,您只需将其存储在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:

即使您知道如何从密钥中检索时间戳,在生产代码中执行此操作也是一个坏主意.时间戳用于生成唯一的,按时间顺序排列的序列.如果Firebase的某个人想出一种更有效的方法(无论是他们偶然选择的效率的主观定义)来实现相同的目标,他们可能会更改 push 的算法.如果您的代码需要时间戳,则应将时间戳添加到数据中.不依赖于它是否是密钥的一部分.

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.

更新

Firebase记录了 Firebase推送ID背后的算法.但是上述建议仍然存在:请勿将其用作存储日期的替代方法.

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.

这篇关于您可以从Firebase实时数据库密钥获取时间戳吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆