返回

Firestore 获取时间戳时的 ClassCastException 问题解决方法

java

Firestore 中获取时间戳时的 ClassCastException 解决方案

问题

在 Spring Boot 中从 Firestore 数据库获取时间戳时,您可能会遇到以下错误:

java.lang.ClassCastException: class java.util.Date cannot be cast to class com.google.cloud.Timestamp

此错误表明您尝试将 Date 对象转换为 Timestamp 对象,但这两者是不兼容的类型。

解决方案

要解决此问题,请遵循以下步骤:

  • 正确导入包: 确保您已正确导入了 com.google.cloud.Timestamp 包。
  • 使用 getTimestamp() 方法: 要从 Firestore 文档中获取时间戳,请使用 getTimestamp() 方法,而不是 getDate() 方法。示例:
Timestamp timestamp = document.getTimestamp("created_time").toDate();

getTimestamp() 方法返回一个 Timestamp 对象,您可以将其转换为 Date 对象以进行处理。

完整代码示例:

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()) {
            Timestamp timestamp = document.getTimestamp("created_time").toDate();
            System.out.println("Timestamp: " + timestamp);
        } else {
            System.out.println("Document not found!");
        }
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }

    return null;
}

其他提示

  • 确保您的 Firestore 版本是最新的。
  • 检查您的代码中是否有任何类型转换错误。
  • 如果问题仍然存在,请尝试清除 IDE 缓存或重新启动应用程序。

常见问题解答

  1. 为什么我不能将 Date 对象直接转换为 Timestamp 对象?
    DateTimestamp 是不同的类型,具有不同的表示和处理方式。

  2. getTimestamp() 方法返回 Timestamp 对象,但为什么我可以将其转换为 Date 对象?
    Timestamp 对象可以通过 toDate() 方法轻松转换为 Date 对象,以方便处理和兼容性。

  3. 如果我需要在 Firestore 中存储和检索时间戳,我应该使用什么类型?
    推荐在 Firestore 中使用 Timestamp 类型来存储和检索时间戳。

  4. 如果我遇到其他类型转换错误,该如何处理?
    仔细检查您的代码中的类型,并确保您正在尝试转换正确的类型。

  5. 还有什么需要注意的吗?
    确保您始终使用正确的包和方法来处理 Firestore 数据,以避免任何类型转换错误或其他问题。

结论

遵循本文中概述的步骤,您可以解决从 Firestore 获取时间戳时的 ClassCastException 错误。通过正确使用 getTimestamp() 方法,您可以轻松地获取并处理时间戳,为您的应用添加时间跟踪和记录功能。