如何将 Firestore 时间戳打印为格式化的日期和时间 [英] How to print Firestore timestamp as formatted date and time
问题描述
我的时间戳在 Flutter Firestore 快照中返回 Timestamp(seconds=1560523991, nanoseconds=286000000)
.
My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000)
in a Flutter Firestore snapshot.
我想将其打印为格式正确的日期和时间.
I want to print it as properly formatted date and time.
我正在使用 DateTime.now()
在 Firestore 中存储当前 DateTime,同时创建新记录并使用 Firestore 快照检索它,但我无法转换为格式化的日期时间.我使用 lib intl.dart
进行格式化.
I'm using DateTime.now()
to store current DateTime in Firestore while creating new records and retrieving it using Firestore snapshot but I am not able to convert to into formatted date time. I'm using lib intl.dart
for formatting.
保存数据的代码
d={'amount':amount,
'desc':desc,
'user_id':user_id,
'flie_ref':url.toString(),
'date':'${user_id}${DateTime.now().day}-${DateTime.now().month}-${DateTime.now().year}',
'timestamp':DateTime.now()
return Firestore.instance.collection('/data').add(d).then((v){return true;
}).catchError((onError)=>print(onError));
});
Accessing with
FutureBuilder(
future: Firestore.instance
.collection('data')
.where('user_id', isEqualTo:_user_id)
.getDocuments(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return Container(
child: Center(child: CircularProgressIndicator()));
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return Column(
children: <Widget>[
Text(DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toString())]);
....
抛出的错误是
无效的日期格式.
我期待的输出是:'Jan 17, 2019, 2:19 PM'
推荐答案
当我们将 DateTime 对象推送到 Firestore 时,它会在内部将其转换为它自己的 timestamp 对象并存储它.
When we push the DateTime object to Firestore, it internally converts it to it's own timestamp object and stores it.
从 Firestore 获取时间戳后将其转换回日期时间的方法:
Firestore 的 timestamp 包含一个名为 toDate() 的方法,该方法可以转换为 String,然后可以将该 String 传递给 DateTimeparse 方法转换回 DateTime
Firestore's timestamp contains a method called toDate() which can be converted to String and then that String can be passed to DateTime's parse method to convert back to DateTime
DateTime.parse(timestamp.toDate().toString())
这篇关于如何将 Firestore 时间戳打印为格式化的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!