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

查看:26
本文介绍了您可以从 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+"
"+new Date(timestamp));
  alert(timestamp+"
"+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天全站免登陆