【问题标题】:Saving TimeStamp as a negative value using ServerValue.TIMESTAMP in FireBase Database在 FireBase 数据库中使用 ServerValue.TIMESTAMP 将时间戳保存为负值
【发布时间】:2018-08-11 09:34:58
【问题描述】:

我想按降序将数据保存在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);

    }

【问题讨论】:

    标签: android firebase-realtime-database timestamp


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2017-12-25
      相关资源
      最近更新 更多