有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓设备中从Firestore获取服务器时间戳?

这与这个问题有关:How can I get Timestamp from Firestore server without bothering for the case when device clock is out of sync with Firestore

我知道FieldValue.serverTimestamp()可以用于在执行数据库操作时在Firestore服务器中生成时间戳。我想了解如何在没有任何数据库相关操作的情况下,以Date/Timestamp格式从特定设备中的Firestore数据库获取时间戳


共 (2) 个答案

  1. # 1 楼答案

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

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

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

    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对象,应该按照我在以下帖子中的回答设置日期:

    编辑:

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

    您无法做到这一点,因为时间戳值完全由Firebase服务器生成。换句话说,当写入操作发生时,将生成该时间戳。您无法在客户机上模拟这种情况,这是有意义的,因为您自己无法随机生成服务器时间戳。只有Firebase服务器可以做到这一点。如果您需要一个特定的时间戳,您应该而不是那样生成它。由于该属性的类型为Date,因此可以将其设置为任何您喜欢的日期。因此,与其让Firestore决定生成什么时间戳,不如自己设置Date

  2. # 2 楼答案

    如果不使用数据库操作,就无法从Firestore获取服务器时间戳

    相反,您可以编写一个返回当前时间的Cloud Function(可能是HTTP triggercallable type function),并直接从客户端调用该时间戳。这避免了必须使用数据库,并且您将得到相同的时间,因为所有Google服务都具有同步时钟

    请记住,通过网络的往返将导致客户端接收到服务器时间的稍微延迟视图,因为您不知道通过网络返回响应需要多长时间