你能从 Firebase 实时数据库密钥中获取时间戳吗?

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

根据此blog post,使用时间戳创建 firebase 数组键:

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

有没有办法恢复这个时间戳以供以后使用,给定密钥?

正如我在评论中所说,您不应依赖于从生成的 ID 中解码时间戳。取而代之的是,您应该将其简单地存储在 Firebase 中的 属性 中。

也就是说,事实证明要取回时间戳相当容易:

// 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));
}

我会重复我的评论,以防万一有人认为将此代码用于任何其他用途而不是作为逆向工程练习是个好主意:

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 已记录 the algorithm behind Firebase push IDs。但上述建议仍然存在:不要将其用作存储日期的替代方法。

这是 在 Swift 中重写的版本(撰写本文时为 4.2。)

需要说明的是,我的用例是在没有时间戳的情况下修补我的旧模型(createdAtupdatedAt。)我可以在其中放入随机日期以保存我有些头疼。但这与他们的模型无关。根据我从其他文章中读到的内容,我知道这些自动 ID 中包含了时间元素。

let PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"

func decode(autoId: String) -> TimeInterval {
  let substring = autoId.substring(toIndex: 8)
  var timestamp = 0
  for i in 0..<substring.length {
    let c = Character(substring[i])
    timestamp = (timestamp * 64) + PUSH_CHARS.firstIndex(of: c)!.encodedOffset
  }
  return TimeInterval(exactly: timestamp)!
}

在此处获取 Playground 就绪代码:https://gist.github.com/mkval/501c03cbb66cef12728ed1a19f8713f7

并且在python

PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"

def get_timestamp_from_id(id):
    timestr = id[0:8]
    timestamp = 0
    for idx, ch in enumerate(timestr):
        timestamp = timestamp * 64 + PUSH_CHARS.index(ch)
    return timestamp/1000