C# Visual Studio项目中Firestore添加timestamp字段方法
C# 操作Firestore添加Timestamp时间戳字段实现方案
针对你当前基于字典结构写入reports集合的代码,可根据业务场景选择对应实现:
方案1:使用Firestore服务端生成的标准时间戳(推荐)
该方案生成的是Firestore服务器接收写入请求时的权威时间,完全不受客户端本地时间偏差、时区设置错误的影响,是绝大多数业务场景的首选。
你只需要在现有数据字典中新增时间戳字段,值传入FieldValue.ServerTimestamp即可,SDK会自动识别该标识,在写入完成后填充服务端时间,字段类型自动映射为Firestore原生Timestamp类型。
修改后的核心代码如下:
// 确保已引入对应命名空间 using Google.Cloud.Firestore; CollectionReference coll = database.Collection("reports"); Dictionary<string, object> data1 = new Dictionary<string, object>() { {"fileId", fileId}, {"fileName", fileName}, {"type", type}, {"userId", userId}, {"url", urlReport }, {"plantId", plantId }, // 新增服务端时间戳字段 {"timestamp", FieldValue.ServerTimestamp} }; // 记得await异步方法,避免写入操作未执行完成就被中断 await coll.AddAsync(data1);
方案2:写入自定义指定时间
如果业务需要存储客户端侧生成的指定时间,直接在字典中传入DateTime或DateTimeOffset类型的值即可,SDK会自动将其转换为Firestore Timestamp类型存储:
// 示例1:存储客户端当前UTC时间 {"timestamp", DateTimeOffset.UtcNow} // 示例2:存储自定义指定时间 {"timestamp", new DateTimeOffset(2024, 6, 1, 0, 0, 0, TimeSpan.Zero)}
补充:强类型实体类映射场景的配置方式
如果后续你改用强类型实体类代替字典做数据写入,只需要给对应时间属性添加[ServerTimestamp]特性,即可实现写入时自动填充服务端时间,无需手动赋值:
[FirestoreData] public class Report { [FirestoreProperty("fileId")] public string FileId { get; set; } [FirestoreProperty("fileName")] public string FileName { get; set; } // 其余业务属性省略... [FirestoreProperty("timestamp")] [ServerTimestamp] // 配置该特性后自动填充服务端时间 public Timestamp? CreateTimestamp { get; set; } }
内容的提问来源于stack exchange,提问作者Nicola Rigoni
相关产品推荐
相关产品推荐

