Firebase Flutter中如何将时间存储为Timestamp类型?
问题:如何将Firestore的time字段保存为Timestamp类型?
我使用以下方法向Firestore发送时间数据,但集合中的time字段类型为int:
Map<String, dynamic> Qnote= { "note": note, "sender": username, "uid": uid, "time": DateTime.now().microsecondsSinceEpoch, // <---- here }; FirebaseFirestore.instance.collection("Note").doc(noteId).collection("QuickNote").add(Qnote);
请问如何将time字段以Timestamp类型保存到集合中?
解决方案
有两种常用方式可以将time字段保存为Firestore的Timestamp类型:
1. 转换本地时间为Timestamp
直接把当前DateTime对象转换成Firestore的Timestamp类型,替换原有的时间戳写法即可:
Map<String, dynamic> Qnote= { "note": note, "sender": username, "uid": uid, "time": Timestamp.fromDate(DateTime.now()), // 转换为Timestamp类型 }; FirebaseFirestore.instance.collection("Note").doc(noteId).collection("QuickNote").add(Qnote);
2. 使用Firestore服务器时间(推荐跨时区场景)
如果需要避免客户端本地时间偏差,希望直接采用Firestore服务器的当前时间,可以用FieldValue.serverTimestamp():
import 'package:cloud_firestore/cloud_firestore.dart'; // 确保导入Firestore包 Map<String, dynamic> Qnote= { "note": note, "sender": username, "uid": uid, "time": FieldValue.serverTimestamp(), // 使用服务器时间 }; FirebaseFirestore.instance.collection("Note").doc(noteId).collection("QuickNote").add(Qnote);
以上两种方式都会让Firestore中的time字段显示为Timestamp类型,后续读取数据时也可以直接将其转换为DateTime对象使用。
内容的提问来源于stack exchange,提问作者Harshana
相关产品推荐
相关产品推荐

