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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:39:01