How to set epoch in Firestore using server time

前端 未结 1 1616
星月不相逢
星月不相逢 2021-01-02 08:19

I\'m trying to set the epoch when data is created in Firestore. I\'m looking to get some similar result to what is done in the real-time database, using ServerValue.TI

1条回答
  •  Happy的楠姐
    2021-01-02 08:41

    The object that results from setting a Firestore field with FieldValue.serverTimestamp() is an instance of java.util.Date. When you later read the value, you can get the epoch time using getTime().

    As an example, for a document created like this:

    Map doc = new HashMap<>();
    doc.put("timestamp", FieldValue.serverTimestamp());
    

    The resulting value can be read like this:

    docRef.get().addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                DocumentSnapshot snapshot = task.getResult();
                if (snapshot != null) {
                    Map map = snapshot.getData();
                    Date date = (Date) map.get("timestamp");
                    Log.d(TAG, "date=" + date);
                    Log.d(TAG, "time=" + date.getTime());
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get() failed with ", task.getException());
            }
        }
    });
    

    0 讨论(0)
提交回复
热议问题