【问题标题】:Get changes based on uploaded time from firebase根据从 firebase 上传的时间获取更改
【发布时间】:2021-09-04 19:11:24
【问题描述】:

我已经使用 firebase 初始化了一个实时数据库,我正在使用检测数据库的实时更改

const ref = firebase.database().ref("test");

ref.on('value', function(dataSnapshot){
    console.log(dataSnapshot.val())
});

但这会按升序返回我的值。而我希望它根据时间返回。我尝试使用时间:00:00 (IST) 格式,但如果数据标记为 11:59(上午)和另一个 01:02(下午),这将首先返回第二条消息。

解决此问题的最佳方法是什么?

示例数据是 =>

在我的数据库中 =>

【问题讨论】:

  • "我尝试使用时间" => 你到底是什么意思?我们在您的数据库中的不同消息中看不到任何时间字段。那你怎么能按时排序呢?
  • 在数据库中你会看到那些孩子 - “akshat”、“utkarsh”、“zain” 我用 IST 替换它们我没有显示它,因为我认为它是可以理解的,对不起我的错..

标签: javascript firebase sorting


【解决方案1】:

不清楚你说的时间升序是什么意思

您的示例数据均未提及时间。它们只是用户名和文本。

如果要正确排序时间,最好使用 ISO 日期格式

这会将 1:02 pm 存储为 13:02,它将在 11:59 之后排序。其分选特性理想。

使用国际时间标准来存储您的时间

国际时间标准 UTC 与国家时间相比具有很大优势。它不受地点、政治决定或季节的影响。您始终可以在输入或显示时与用户的本地时间相互转换。

示例

const dateString = (new Date()).toISOString();

console.log(dateString)
// Result: 
// 2021-06-22T14:40:37.985Z



// If you want to use them as Firebase keys, they must not contain a ".", so you might clean it up like this:

const cleanDateString = (new Date()).toISOString().replace(".","-")

console.log(cleanDateString)
// Result: 
// 2021-06-22T14:47:44-445Z

更好的是,使用 Firebase PushID

如果您使用上面的日期和时间系统对单个人的评论进行排序,则可以使用,但如果共享单个空间,则不能作为消息标识符所有人,因为 2 个人最终会在相同的毫秒内发出一条消息,并且会得到相同的消息 ID。

要解决这个问题,最好使用 Firebase Push ID。

这里给出解释:In Firebase when using push() How do I get the unique ID and store in my database

或者来自 Firebase 本身,这里: https://firebase.google.com/docs/database/admin/save-data

【讨论】:

  • 谢谢,我想使用 ISO 可能会解决我的问题,在你的回答中多一个支持你能添加如何使用 javascript 获取 ISO 时间吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多