JavaScript如何将日期转为timestamp并在Firestore云函数中正确存储
问题根因
你代码中date: Date(Date.now())的写法是将Date作为普通函数调用,返回值为字符串类型的日期文本,Firestore会直接按照字符串存储,不会转换为Timestamp类型。
解决方法
Firestore支持两种写入Timestamp的方式,任选其一即可:
- 传入JavaScript原生
Date对象,Firestore会自动将其转换为Timestamp类型存储,写法为new Date()(Date.now()返回的是毫秒时间戳,new Date(Date.now())和直接写new Date()效果完全一致) - 显式调用Firebase Admin SDK内置的Timestamp类生成时间戳,写法为
admin.firestore.Timestamp.now(),兼容性更强,不会受运行环境的Date对象实现差异影响
修改后的代码示例
await admin.firestore() .doc('/buyerProfile/'+response.buyerId) .collection('notifications') .add({ 'type':'New response', 'responseId':response.responseId, 'requestId':response.requestId, 'date': admin.firestore.Timestamp.now(), // 也可替换为 new Date() 'compressedImgUrl':response.compressedImgUrl, 'description':response.description, 'requestPaidFor':request.data().isPaidFor }).then(()=>console.log('Notification created'));
补充说明
如果需要从自定义的时间生成Timestamp,可以使用对应转换方法:
- 从毫秒时间戳转换:
admin.firestore.Timestamp.fromMillis(自定义毫秒时间戳) - 从已有的Date对象转换:
admin.firestore.Timestamp.fromDate(自定义Date对象)
内容的提问来源于stack exchange,提问作者Bright
相关产品推荐
相关产品推荐

