如何从Firestore服务器获取时间戳,而不必担心设备时钟与Firestore不同步的情况 [英] How can I get Timestamp from Firestore server without bothering for the case when device clock is out of sync with Firestore
问题描述
这是对此问题的参考 Firebase时间戳当前时间戳和数据库时间戳错误之间的区别
如果我使用 Timestamp.now()
,在某些情况下设备时钟与Firestore不同步,并且我的时间计算不准确.我想从Firestore服务器获取准确的时间,而不会被不同步的情况所困扰.有什么办法可以做到吗?
If I use Timestamp.now()
there are cases where the device clock is out of sync with Firestore and my time calculations are not accurate. I want to get the exact time from the Firestore server without being bothered by out of sync cases. Is there any way I could do that?
我见过 FieldValue.serverTimestamp()
,但是我找不到一种使用它来计算任何东西的方法,因为它的返回类型是 FieldValue
,而且我无法解析它保存为 Timestamp
.
I have seen FieldValue.serverTimestamp()
but there I cannot find a way to calculate anything using it, since it's return type is FieldValue
and I am unable to parse it to Timestamp
.
推荐答案
一种明显但在经济上不利的方法是写入时间戳的Firestore数据库,然后从那里重新读取.
One obvious but economically adverse way is to write to Firestore Database, the timestamp and read it again from there.
db.collection("TimestampChecker").document("some_string").set(new TimestampGetter()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
db.collection("TimestampChecker").document("some_string").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.getResult()!=null)
{
TimestampGetter timestampGetter = task.getResult().toObject(TimestampGetter.class);
Date dateNow = timestampGetter.getTimestampNow();
}
}
});
}
});
TimestampGetter可以是这样的类:
And TimestampGetter can be a class like this:
public class TimestampGetter {
@ServerTimestamp
private Date timestampNow;
public TimestampGetter(Date timestampNow) {
this.timestampNow = timestampNow;
}
public TimestampGetter() {
}
public Date getTimestampNow() {
return timestampNow;
}
public void setTimestampNow(Date timestampNow) {
this.timestampNow = timestampNow;
}}
这篇关于如何从Firestore服务器获取时间戳,而不必担心设备时钟与Firestore不同步的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!