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

Flutter中如何向Firestore发送用户选定的自定义日期到timestamp类型字段

手动写入自定义日期到Firestore Timestamp字段的方案

你可以通过Firestore SDK自带的Timestamp静态方法,将任意自定义日期转换为Timestamp类型存储,不需要调用Timestamp.now()生成当前时间,写入后控制台显示的格式和你给出的示例完全一致。

实现步骤

  1. 先将用户选定的日期转换为标准JavaScript Date对象,注意匹配你需要的时区
  2. 调用Timestamp.fromDate()方法将Date对象转换为Firestore Timestamp类型
  3. 直接将转换后的Timestamp值写入对应字段即可

代码示例

  • 前端JavaScript写法
// 示例:用户选定的是1946年6月4日 00:00 UTC+5:30
const userPickedDate = new Date('1946-06-04T00:00:00+05:30');
// 转成Firestore Timestamp格式
const dobTimestamp = firebase.firestore.Timestamp.fromDate(userPickedDate);
// 写入Firestore文档
await db.collection('你的集合名').doc('文档ID').set({
  dob: dobTimestamp
});
  • Node.js 后端写法
const { Timestamp } = require('firebase-admin/firestore');

const userPickedDate = new Date('1946-06-04T00:00:00+05:30');
const dobTimestamp = Timestamp.fromDate(userPickedDate);

await db.collection('你的集合名').doc('文档ID').set({
  dob: dobTimestamp
});

其他可用方法

如果你拿到的用户日期是13位毫秒时间戳格式,可以直接用Timestamp.fromMillis(毫秒数)生成对应Timestamp,不需要先转Date对象:

// 示例:1946年6月4日00:00 UTC+5:30对应的毫秒时间戳
const dobTimestamp = Timestamp.fromMillis(-744595800000);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 17:15:02