因此,假设您拥有一个如下所示的数据库架构:
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对象,应该按照以下帖子中我的回答中的说明设置日期:
- 在Firebase Firestore上ServerTimestamp始终为null
编辑:
这个问题强调了在不执行任何数据库相关操作的情况下获取服务器时间戳。
您无法执行此操作,因为该时间戳记值完全由Firebase服务器生成。换句话说,发生写操作时,将生成该时间戳。您无法在客户端上对此进行模拟,这是有道理的,因为您无法自己随机生成服务器时间戳。只有Firebase服务器可以做到这一点。如果你需要一个特定的时间戳,你应该
不会
产生这种方式。由于该属性的类型为
Date,因此您可以将其设置为任意日期。因此,不要让Firestore决定要生成哪个时间戳,而要
Date自己设置。



