如何从Android设备中的Firestore获取服务器时间戳? [英] How to get server Timestamp from Firestore in an android device?

查看:47
本文介绍了如何从Android设备中的Firestore获取服务器时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这与以下问题有关:我了解到FieldValue.serverTimestamp()可用于在执行数据库操作时在Firestore服务器中生成时间戳记.我想了解如何以Date/Timestamp格式从特定设备中的Firestore数据库获取时间戳,而无需任何与数据库相关的操作.

I have understood FieldValue.serverTimestamp() can be used to generate a Timestamp in Firestore server while performing database operations. I want to understand how I can get the timestamp from the Firestore Database in a particular device in a Date/Timestamp format without any database related operation.

推荐答案

因此,假设您拥有一个如下所示的数据库架构:

So assuming you have a database schema that looks like this:

Firestore-root
   |
   --- users (collection)
        |
        --- uidOne (document)
              |
              --- name: "UserOne"
              |
              --- creationDate: January 25, 2020 at 3:37:59 PM UTC+3 //Timestamp

要获取creationDate属性的值作为Date对象,请使用以下代码行:

To get the value of creationDate property as a Date object, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        DocumentSnapshot document = task.getResult();
        if (document.exists()) {
            Date creationDate = document.getDate("creationDate");
            //Do what you need to do with your Date object
        }
    }
});

请记住,为了获得此Date对象,应该按照以下帖子中我的回答中的说明设置日期:

Remember, in order to get this Date object, the date should be set as explained in my answer from the following post:

该问题强调了不执行任何与数据库相关的操作而获取服务器时间戳的方法.

The question emphasized to get the Server Timestamp without performing any database related operation.

您无法执行此操作,因为时间戳值完全由Firebase服务器生成.换句话说,发生写操作时,将生成该时间戳.您无法在客户端上对此进行模拟,这很有意义,因为您无法自己随机生成服务器时间戳.只有Firebase服务器可以做到这一点.如果您需要特定的时间戳,则应该以这种方式生成.由于该属性的类型为Date,因此您可以将其设置为任何您想要的日期.因此,与其让Firestore决定要生成哪个时间戳,不如自己设置Date.

There is no way you can do this since that timestamp value is generated entirely by Firebase servers. In other words, when a write operation takes place, that timestamp is generated. You cannot simulate this on the client and it makes sense since you cannot randomly generate a server timestamp yourself. Only Firebase servers can do that. If you need a particular timestamp, you should not generate it that way. Since that property is of type Date, you can set it with any Date you'll like. So instead of letting Firestore decide what timestamp to generate, set the Date yourself.

这篇关于如何从Android设备中的Firestore获取服务器时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆