如何在android中使用FieldValue.serverTimestamp()来自定义模型类

时间:2017-10-31 12:19:05

标签: android firebase firebase-realtime-database google-cloud-firestore

我使用Firestore作为数据库,现在我想在用户注册时存储服务器时间戳。

来自Firestore doc的

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

但现在我想在我的模特课中加上这个时间戳。

public class UserModel implements Serializable {
    private String name;
    private String uid;
    private String email;
    private String password;
    private long timestamp;

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

我怎样才能做到这一点。 请帮帮我。

4 个答案:

答案 0 :(得分:11)

经过大量研究后,我找到了解决方案。

 @ServerTimestamp
 private Date timestamp;

 public Date getTimestamp() {
     return timestamp;
 }
 public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
 }

并且在调用此类时

UserModel userModel = new UserModel();
userModel.setEmail(email);
userModel.setPassword(password);
userModel.setName(name);
userModel.setUid(uid);

insertUserDataToFireStore(userModel); 

这是我找到解决方案的链接 Click here

答案 1 :(得分:0)

您需要更改以下代码行:

private long timestamp;

private Map<String, String> timestamp;

以下是相应的公开settersgetters

public void setTimestamp(Map<String, String> timestamp) {
    this.timestamp = timestamp;
}
public Map<String, String> getTimestamp() {
    return timestamp;
}

请注意,您将时间戳设置为Map,当您检索时,您将其检索为Long

答案 2 :(得分:0)

private com.google.firebase.Timestamp date;

public yourModel(com.google.firebase.Timestamp date) {
        this.date= date;
}

public com.google.firebase.Timestamp getDate() {
        return date;
}

public void setDate(com.google.firebase.Timestamp date) {
        this.date = date;
}

答案 3 :(得分:-3)

如果您只想要 时间戳 而不是准确的时间事件,那么您可以使用

System.currentTimeMillis();