最佳实践是将数据保存为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";
}
}
Edit:模型类应该如下所示:
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 实时数据库在写入操作期间用作子值时在服务器端转换为数字的令牌。该日期仅在写入操作完成后才会出现在数据库中。
为了得到timestamp
,还有另一种方法,那就是编写一个函数Firebase 的云功能这将很简单:
exports.currentTime = functions.https.onRequest((req, res) => {
res.send({"timestamp":new Date().getTime()})
})
您可以将其托管在 Cloud Function 中并获取服务器时间戳,而无需用户交互。