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

如何在Firestore中存储服务端生成的文档创建时间戳

问题原因

  • Timestamp.now()是客户端本地计算生成的时间戳,和new Date()本质一样,都完全依赖设备本地系统时间,修改本地时间后两个字段自然都会返回错误时间,不符合你要的服务端生成时间的需求。
  • 你需要调用Firestore内置的服务端时间标记方法,让时间由Firestore服务端在写入文档时生成,完全不受客户端本地时间影响。

修正后的代码

import { addDoc, collection, serverTimestamp } from 'firebase/firestore';
import { db } from '../index';

export const storeSomething = async () => {
    const data = {
        clientDate: new Date(),
        // 标记该字段为服务端写入时生成时间
        serverTimestamp: serverTimestamp(),
    };
    
    const someCol = collection(db, 'somecollection');
    const docRef = await addDoc(someCol, data);
};

补充注意点

  • 如果你在客户端监听该文档的实时更新,写入操作触发的第一次本地缓存快照中,serverTimestamp字段会默认返回null,因为此时服务端还没返回写入结果,时间还没生成。
  • 如果你需要本地提前展示估算时间,可以在调用快照的data()方法时传入配置:snapshot.data({ serverTimestamps: 'estimate' }),此时本地会用当前时间估算填充该字段,等服务端结果返回后再自动更新为准确的服务端时间。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 23:12:03