问题描述
当我通过控制面板向Firebase实时数据库添加新值时,我想在特定字段中保存当前日期/时间。
I want to save the current date/time in specific field when I add new value to Firebase Realtime Database via control panel.
我该如何实现?
请帮帮我。
推荐答案
最佳做法是保存你的数据为 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";
}
}
编辑:模型class应如下所示:
The model class should look like this:
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实时数据库在写入操作期间用作子值时Firener实时数据库转换为服务器端号码的标记。写入操作完成后,日期仅出现在数据库中。
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.
要获得时间戳
,还有另一个方法,即在中编写一个函数,它将是简单如下:
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()})
})
您可以在云功能中托管此功能,并在无需用户交互的情况下获取服务器时间戳。
You can host this in Cloud Function and get the server timestamp without user interaction.
这篇关于将新值添加到Firebase实时数据库时如何保存当前日期/时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!