gpt4 book ai didi

java - 当我向 Firebase 实时数据库添加新值时如何保存当前日期/时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:50:14 25 4
gpt4 key购买 nike

当我通过控制面板向 Firebase 实时数据库添加新值时,我想在特定字段中保存当前日期/时间。

我怎样才能做到这一点?

请帮帮我。

最佳答案

最佳做法是将数据保存为 TIMESTAMP,例如 ServerValue.TIMESTAMP

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("timestamp", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);

还请记住,当您设置 TIMESTAMP 时,您将其设置为 Map,但是当您检索它时,您将其检索为 Long。要取回数据,我建议您使用这种方法:

public static String getTimeDate(long timestamp){
try{
DateFormat dateFormat = getDateTimeInstance();
Date netDate = (new Date(timestamp));
return dateFormat.format(netDate);
} catch(Exception e) {
return "date";
}
}

编辑模型类应该如下所示:

public class YourModelClass {
//private fields
private Map<String, String> timestamp;

public YourModelClass() {}

//public setters and getters for the fields

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

请记住,ServerValue.TIMESTAMP 只是一个 token ,Firebase 实时数据库在写入操作期间用作子值时会在服务器端将其转换为数字。只有在写入操作完成后,日期才会出现在数据库中。

要获取时间戳,还有另一种方法,就是在Cloud Functions for Firebase中写一个函数。它会很简单:

exports.currentTime = functions.https.onRequest((req, res) => {
res.send({"timestamp":new Date().getTime()})
})

您可以在 Cloud Function 中托管它并在无需用户交互的情况下获取服务器时间戳。

关于java - 当我向 Firebase 实时数据库添加新值时如何保存当前日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43584244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com