Firestore日期格式问题:自定义时间对象无法写入数据库
Firestore日期格式写入问题解决
你完全可以继续使用原生Date对象写入Firestore,这是官方推荐的简便方式,不需要手动转换为自定义的{seconds, nanoseconds}结构。
为什么自定义日期对象写入失败?
Firestore的Timestamp类型不是普通键值对对象,它需要是Firebase SDK提供的Timestamp类实例。你自己构造的{seconds: 1722940200, nanoseconds: 0}只是普通JavaScript对象,Firestore SDK不会将其识别为Timestamp类型,因此无法正确写入。
正确的日期写入方式
有两种官方支持的写法:
直接使用原生
Date对象(推荐)
你最初的写法完全正确,Firebase SDK会自动将Date对象转换为Firestore的Timestamp类型存储,读取时也能自动转回Date或Timestamp。保持原有data结构即可:const data = { title: "data", startDate: new Date("2024-08-10T11:30:00Z"), endDate: new Date("2024-08-10T12:00:00Z"), allDay: false, notes: "data" };显式使用Firestore Timestamp实例
如果需要手动控制Timestamp,必须使用SDK提供的Timestamp类创建实例,示例如下:import { Timestamp } from "firebase/firestore"; // 按你的实际导入方式调整 const startDate = Timestamp.fromDate(new Date("2024-08-10T11:30:00Z")); const endDate = Timestamp.fromDate(new Date("2024-08-10T12:00:00Z")); const data = { title: "fff", startDate, endDate, allDay: false, notes: "fff" };用这种方式构造的data写入Firestore后,会被正确识别为Timestamp类型。
你的写入代码还有一处小问题
注意你代码里的await setDoc(...).then(handleSuccess())写法有误:handleSuccess()是直接调用函数,而非传入回调。正确写法应为:
try { await setDoc(doc(db, "appointments", id), data, { merge: true }); handleSuccess(); // 写入成功后再执行 } catch (e) { handleError(e); }
原写法会导致handleSuccess()在setDoc未完成时就执行,可能让你误以为写入失效,这一点需要修正。
内容的提问来源于stack exchange,提问作者Kiszuriwalilibori
相关产品推荐
相关产品推荐

