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

Lee*_*nah 6 java android firebase firebase-realtime-database

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

我怎样才能做到这一点?

请帮我.

Ale*_*amo 17

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

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

还要记住,当你设置它时TIMESTAMP,你将其设置为a 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";
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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;}
}
Run Code Online (Sandbox Code Playgroud)

请记住,ServerValue.TIMESTAMP这只是Firebase实时数据库在写入操作期间用作子值时转换为服务器端号码的标记.写操作完成后,日期仅出现在数据库中.

为了得到这个timestamp,还有另一种方法,即在Cloud Functions for Firebase中编写一个功能,它将像以下一样简单:

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

您可以在云功能中托管此功能,并在无需用户交互的情况下获取服务器时间戳.