You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java LocalDateTime如何将时间以Timestamp格式存入Firestore?

问题原因

Firestore 原生仅支持 com.google.firebase.Timestamp 作为时间类型的存储格式,并未对 Java 8+ 推出的 LocalDateTime 做序列化适配,因此你直接将 LocalDateTime 实例存入Map时,Firestore 会将其内部的年、月、日、时、分等字段拆解为Map结构存储,也就出现了你截图里的非预期存储结果。

解决方案

不需要替换 LocalDateTime,只需要在写入 Firestore 之前,将 LocalDateTime 转换为 Firestore 支持的 Timestamp 类型即可,转换逻辑如下:

// 1. 给无时区的LocalDateTime绑定时区,这里使用系统默认时区,也可指定固定时区 如ZoneId.of("Asia/Shanghai")
ZoneId zoneId = ZoneId.systemDefault();
// 2. 转换为Instant时间戳
Instant instant = localDateTime.atZone(zoneId).toInstant();
// 3. 转换为Firestore支持的Timestamp类型
com.google.firebase.Timestamp firestoreTime = com.google.firebase.Timestamp.fromInstant(instant);

修改你的存储代码对应部分即可:

CollectionReference admin = FirebaseFirestore.getInstance().collection("Admin");

Map<String, Object> electionEndTime = new HashMap<>();
// 替换原来的localDateTime为转换后的Timestamp
electionEndTime.put("electionEndTime", firestoreTime);

admin.get()
        .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                String adminEmail = "";
                List<DocumentSnapshot> documentSnapshots = queryDocumentSnapshots.getDocuments();
                for (DocumentSnapshot documentSnapshot : documentSnapshots) {
                    adminEmail = documentSnapshot.getId();
                }

                admin.document(adminEmail).set(electionEndTime, SetOptions.merge());
            }
        });

读取时转换回LocalDateTime

后续你从Firestore读取该字段时,可通过以下逻辑转回LocalDateTime使用:

// 从文档中取出Timestamp
com.google.firebase.Timestamp time = (com.google.firebase.Timestamp) documentSnapshot.get("electionEndTime");
// 转换回LocalDateTime,注意时区要和存入时保持一致
LocalDateTime localDateTime = time.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

注意事项

  • 存入和读取时使用的时区必须统一,否则会出现时间偏移问题
  • 若你的应用服务跨时区使用,建议统一使用UTC时区(ZoneId.of("UTC"))做转换

内容的提问来源于stack exchange,提问作者HeroreH29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:36:03