Java 发送数据时,从 Android 应用中的 Firebase 检索 ServerValue.Timestamp
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25744398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve ServerValue.Timestamp from Firebase in Android app, when data is sent
提问by user3537089
I would like to know how to use Firebase's ServerValue.TIMESTAMP method, when I want to create a timestamp at the Firebase server, and then retrieve it to the local client.
我想知道如何使用 Firebase 的 ServerValue.TIMESTAMP 方法,当我想在 Firebase 服务器上创建时间戳,然后将其检索到本地客户端时。
In Firebase guides, only javascript has a more detailed description of this case, but I'm having a hard time figureing how to translate this in to my Android appliction.
在 Firebase 指南中,只有 javascript 对这种情况有更详细的描述,但我很难弄清楚如何将其转换为我的 Android 应用程序。
Thanks in advance!
提前致谢!
采纳答案by Ossama
Firebase.ServerValue.TIMESTAMP
is set as a Map
(containing {.sv: "timestamp"}
) which tells Firebase to populate that field with the server's time. When that data is read back, it is the actual unix time stamp which is a Long
.
Firebase.ServerValue.TIMESTAMP
设置为Map
(包含{.sv: "timestamp"}
),它告诉 Firebase 用服务器的时间填充该字段。当该数据被读回时,它是实际的 unix 时间戳,它是一个Long
.
Something like this will work:
像这样的事情会起作用:
Firebase ref = new Firebase("https://YOUR-FIREBASE.firebaseio.com");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
Long timestamp = (Long) snapshot.getValue();
System.out.println(timestamp);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
ref.setValue(ServerValue.TIMESTAMP);
For another example, you can see my answer to this question: Android chat crashes on DataSnapshot.getValue() for timestamp
再举一个例子,你可以看到我对这个问题的回答:Android chat crashes on DataSnapshot.getValue() for timestamp
回答by Yaniv
I know this question already been answered, but I wanted to share my version of the solution.
我知道这个问题已经得到回答,但我想分享我的解决方案版本。
When I use the server's timestamp, i usually need to use it more than once, i.e I have some kind of startTime
and endTime
which both depend on the server's time, where startTime
is NOW
and endTime
is X seconds / minutes / hours after startTime
, so to spare the multiple requests to the server I save the server's time in a root child called serverTime
in the database, and I use it to set all dependent values.
当我使用服务器的时间戳,我通常需要多次使用它,即我有某种startTime
与endTime
这都依赖于服务器的时间,这里startTime
是NOW
和endTime
是X秒/分钟/小时startTime
,所以做足了多个请求到服务器,我将服务器的时间保存serverTime
在数据库中调用的根子节点中,并使用它来设置所有相关值。
Another thing, because of the way Firebase works with the ServerValue.Timestamp
, eventually it fires 2 events (added and changed), the first one with local timestamp and the second with the actual server's timestamp. So to overcome the issue of not receiving the correct time I added a simple OnCompleteListener
.
另一件事,由于 Firebase 使用 的方式ServerValue.Timestamp
,最终它会触发 2 个事件(添加和更改),第一个带有本地时间戳,第二个带有实际服务器的时间戳。所以为了克服没有收到正确时间的问题,我添加了一个简单的OnCompleteListener
.
A short example code:
一个简短的示例代码:
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ServerValue;
import com.google.firebase.database.ValueEventListener;
public class ServerTime {
public interface OnTimeRetrievedListener {
void onTimeRetrieved(Long timestamp);
}
private final DatabaseReference db;
public ServerTime(DatabaseReference db) {
this.db = db.child("serverTime");
}
/**
* Gets the server's timestamp in milliseconds.
* @param listener {@link OnTimeRetrievedListener}
*/
public void getTime(final OnTimeRetrievedListener listener) {
if (listener == null) {
return;
}
db.setValue(ServerValue.TIMESTAMP).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
db.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
listener.onTimeRetrieved(dataSnapshot.getValue(Long.class));
}
@Override
public void onCancelled(DatabaseError databaseError) { }
});
}
});
}
}
回答by David Vávra
If you don't want to write to database to figure out the timestamp, you can get instant approximation of it. Works even offline and it's good enough for most cases.
如果您不想写入数据库来计算时间戳,您可以立即获得它的近似值。甚至可以脱机工作,对于大多数情况来说已经足够了。
Read value
读取值
/.info/serverTimeOffset
And add it to new Date().time()
并将其添加到 new Date().time()
回答by Qamar
First, send an object to the firebase server
首先,向firebase服务器发送一个对象
FirebaseDatabase.getInstance().getReference("serverTimeTest").setValue(new KKModel());
FirebaseDatabase.getInstance().getReference("serverTimeTest").setValue(new KKModel());
Model class
模型类
class KKModel{
public String someField = "value";
public Object creationDate = ServerValue.TIMESTAMP;
public String creationDate() {
return SimpleDateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(creationDate);
}
}
Usage
用法
object.creationDate()
working fine test results "9/6/18"
object.creationDate()
运行良好的测试结果 "9/6/18"