我将下面的Map showen保存到firestore中,但我也想保存一个时间戳,该时间戳应该包含用户使用日期和时间选择器选择的时间和日期。日期已经是"dd.MM.yyyy"格式,时间大约是"下午6:58"。日期是变量date
,时间是变量time
。如何保存值为time
和date
的时间戳?
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time: '//here I want to safe the timestamp
};
Firestore.instance
.collection('seller')
.document(documentID)
.collection('test')
.add(data);
}
如果你想使用服务器生成的值,这会更好,这样你就不依赖于设备时间,请使用这个:
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time': FieldValue.serverTimestamp(),
};
Firestore.instance
.collection('seller')
.document(documentID)
.collection('test')
.add(data);
但请注意,如果您在将此文档写入集合时有一个活动的集合快照订阅,则您将获得一个time
的null
值的快照(因为乐观提交(,然后当您从服务器获取数据时,您将获得实际的毫秒值。
EDIT:您可以通过将此写入作为事务的一部分来防止乐观提交为时间戳发出null
值。
我建议将其转换为epoch时间,因为int将其存储在云中,并在获取后重新转换为DateTime。
示例:
// Convert DateTime to int
int time = DateTime.now().millisecondsSinceEpoch;
Map<String, dynamic> data = {
'name': userName,
'userUID': userUIDglobal,
'time': time
};
// To safely convert it back to DateTime
DateTime fetchedTime = DateTime.fromMillisecondsSinceEpoch(data['time']);