首页 > 解决方案 > 在 FireBase 数据库中使用 ServerValue.TIMESTAMP 将时间戳保存为负值

问题描述

我想按降序将数据保存在firebase数据库中,我发现解决方案是添加一个带有负值的timeStamp字段,但是使用ServerValue.TIMESTAMP 只以正的方式保存值,那么我该如何保存我的 FireBase 中的负时间戳:

型号代码:

public class Book{
    Object createdTimestamp;
    String nom_livre;
    String desc_livre;
    String prix_livre;
    String id_book;
    String id_user;

    public Book() {
        super();
    }

    public Book(String nom_livre, String desc_livre, String prix_livre, String id_book,String id_user,  Object createdTimestamp) {
        super();

        this.nom_livre = nom_livre;
        this.desc_livre = desc_livre;
        this.prix_livre = prix_livre;
        this.id_book = id_book;
        this.id_user=id_user;
        this.createdTimestamp=  createdTimestamp;

    }
    @Exclude
    public long getCreatedTimestampLong(){
        return (long)createdTimestamp;
    }

   //other getters and setters
}

在 fireBase 添加数据的代码,我的情况是我正在 addBookActivity 上创建一本书:

private void createBook(String nom_livre, String desc_livre,String prix_livre,Object createdTimestamp) {

        bookInfos=new Book(nom_livre,desc_livre,prix_livre,idLivre,id, ServerValue.TIMESTAMP );

            myRefBook.child(idBook).setValue(bookInfos);

    }

在此处输入图像描述

标签: androidfirebase-realtime-databasetimestamp

解决方案


您有两个选择,在您最初将常规时间戳编号写入正数之后,它们都需要第二次写入数据库。

如果您只想在客户端应用程序上写入数据,您可以createdTimestamp按现在的方式写入数据,然后通过侦听您刚刚写入的位置将该值读回客户端。读回后,您将获得实际的时间戳值。然后,您可以轻松地计算负数并将其写回您想要的位置(也许revCreatedTimestamp,如果您使用它按时间倒序排序)。

您的另一个选择是使用Cloud Functions for Firebase编写一个实时数据库触发器,以响应与您为该书生成的字符串的/books/{book_id}位置相匹配的写入。book_id然后,该触发器可以捕获时间戳并在同一位置写回否定版本。


推荐阅读