尝试使用springboot从firestore获取时间戳

问题描述 投票:0回答:1

我试图从集合中的文档获取时间戳,但出现错误:

错误 26920 --- java.lang.ClassCastException:类 java.util.Date 无法转换为类 com.google.cloud.Timestamp(java.util.Date 位于加载程序“bootstrap”的模块 java.base 中;

com.google.cloud.Timestamp 位于加载程序“app”的未命名模块中)] 其根本原因

那么我做错了什么?

这是代码

    public Timestamp getUsers() throws ExecutionException, InterruptedException {
        DocumentReference docRef = firestore.collection("usuarios").document("XHlUdE5516ZT2EEoBBiXvW0De4z1");
        ApiFuture<DocumentSnapshot> future = docRef.get();
        
        try {
            DocumentSnapshot document = future.get();
            if (document.exists()) {
                Date timestamp = document.getDate("created_time");
                System.out.println("Timestamp: " + timestamp);
            } else {
                System.out.println("Document not found!");
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        
        
return null;
    }

我已经尝试了一切方法来更改时间戳为日期,只留下时间戳等等......

java spring-boot google-cloud-firestore
1个回答
0
投票

您收到以下错误:

java.lang.ClassCastException:类 java.util.Date 无法转换为类 com.google.cloud.Timestamp(java.util.Date 位于加载程序“bootstrap”的 java.base 模块中;

因为下面这行代码:

Date timestamp = document.getDate("created_time");

您尝试将Firestore Timestamp类型的对象保存到声明为Date类型的变量中,这在Java中是不可能的,因为这两个类之间没有继承关系,因此会出现错误。确实,方法的名称表明应该返回的对象应该是Date类型,但是根据Firetore支持的数据类型,您可以使用“日期和时间”类型的字段,这意味着您的

created_time
字段是
Firestore Timestamp
而不是
Date

正如 @DougStevenson 在他的评论中提到的,您唯一的选择是保存 toDate() 方法。所以在代码中,它应该是这样的:

Timestamp timestamp = document.getDate("created_time");
Date createdTime = timestamp.toDate(); 
© www.soinside.com 2019 - 2024. All rights reserved.