在Firebase Firestore上ServerTimestamp始终为null [英] ServerTimestamp is always null on Firebase Firestore

查看:115
本文介绍了在Firebase Firestore上ServerTimestamp始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Firebase Firestore在Android客户端中添加时间戳字段.

I am trying to add a timestamp field in an Android client with Firebase Firestore.

根据文档:

用于标记要用服务器填充的日期字段的注释 时间戳记.如果正在写入的POJO包含null @ServerTimestamp注释的字段,它将被替换为 服务器生成的时间戳.

Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.

但是当我尝试时:

@ServerTimestamp
Date serverTime = null; // I tried both java.util.Date and java.sql.Date

//...

Map<String, Object> msg = new HashMap<>();
// ... more data
msg.put("timestamp", serverTime);

在Cloud Firestore数据库上,此字段始终为null.

On the Cloud Firestore database this field is always null.

推荐答案

这不是将时间和日期添加到Cloud Firestore数据库的正确方法.最佳实践是拥有一个模型类,在其中可以添加类型为Date的日期字段以及注释.这是您的模型类的外观:

That is not the correct way of how to add the time and date to a Cloud Firestore database. The best practice is to have a model class in which you can add a date field of type Date together with an annotation. This is how your model class should look like:

import java.util.Date;

public class YourModelClass {
    @ServerTimestamp
    private Date date;

    YourModelClass() {}

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

YourModelClass类的对象上创建时,无需设置日期. Firebase服务器将读取您的date字段,因为它是一个ServerTimestamp(请参见注释),并且它将相应地使用服务器时间戳填充该字段.

When you create on object of YourModelClass class, there is no need to set the date. Firebase servers will read your date field, as it is a ServerTimestamp (see the annotation), and it will populate that field with the server timestamp accordingly.

另一种方法是使用 FieldValue.serverTimestamp()方法:

Another approach would be to use FieldValue.serverTimestamp() method like this:

Map<String, Object> map = new HashMap<>();
map.put("date", FieldValue.serverTimestamp());
docRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}

这篇关于在Firebase Firestore上ServerTimestamp始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆