向 Firebase 实时数据库添加新值时如何保存当前日期/时间 [英] How to save the current date/time when I add new value to Firebase Realtime Database

查看:31
本文介绍了向 Firebase 实时数据库添加新值时如何保存当前日期/时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to save the current date/time in specific field when I add new value to Firebase Realtime Database via control panel.

我怎样才能做到这一点?

How can I achieve that?

请帮帮我.

推荐答案

最佳做法是将您的数据保存为 TIMESTAMP 像这样 ServerValue.TIMESTAMP.

The best practice is to save your data as a TIMESTAMP like this ServerValue.TIMESTAMP.

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

还要记住,当你设置TIMESTAMP时,你将它设置为一个Map,但是当你检索它时,你将它检索为一个Long代码>.要取回数据,我建议您使用此方法:

Also remember, when you set the TIMESTAMP, you set it as a Map, but when you retrieve it, you retrieve it as a Long. To get the data back, i suggest you use this method:

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 只是 Firebase 实时数据库在写入操作期间用作子值时在服务器端转换为数字的令牌.日期只在写操作完成后出现在数据库中.

Remember, ServerValue.TIMESTAMP is just a token that Firebase Realtime Database converts to a number on server side when it's used as a child value during write operation. The date only appears in the database after the write operation completes.

要获得 timestamp,还有另一种方法,即在 适用于 Firebase 的 Cloud Functions 功能,就像:

To get the timestamp, there is also another approach, which would be to write a frunction in Cloud Functions for Firebase and it will be as easy as:

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

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

You can host this in Cloud Function and get the server timestamp without user interaction.

这篇关于向 Firebase 实时数据库添加新值时如何保存当前日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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