【发布时间】:2019-09-22 04:11:49
【问题描述】:
如何将 Firestore 时间戳更改为“2 天前或 1 小时前”之类的内容?我尝试直接显示它,但出来的数据是像Timestamp(seconds=1556459022, nanosecond=0)这样的字符串。
怎么做?
【问题讨论】:
如何将 Firestore 时间戳更改为“2 天前或 1 小时前”之类的内容?我尝试直接显示它,但出来的数据是像Timestamp(seconds=1556459022, nanosecond=0)这样的字符串。
怎么做?
【问题讨论】:
我就是这样解决的。导入以下包:
import 'package:timeago/timeago.dart' as timeago;
现在,从 Firestore 获取时间戳。例如,字段名'timestamp',参考如下代码:
final document = Firestore.instance.collection("yourCollectionName").snapshots();
现在使用以下方法访问您的时间戳:
`Timestamp timestamp = document['timestamp'];
最后,在应用中显示结果。示例:
Text(timeago.format(DateTime.tryParse(timestamp.toDate().toString())).toString());
【讨论】:
Firestore 的时间戳有一个 toDate() 方法,该方法将返回一个 dart DateTime 对象。
您可以使用常规 dart 解决方案,例如 DateFormat 或 timeago 库来显示它:
timeago.format(firestoreTimestamp.toDate());
【讨论】:
firestoreTimestamp ?我可以使用 DocumentSnapshot 吗?
data 映射的文档快照。在地图内,您应该在相应字段名称下找到时间戳,例如documentSnapshot.data['FIELD_NAME_HERE'].