如何将Firestore时间戳打印为格式化的日期和时间 [英] How to print Firestore timestamp as formatted date and time

查看:98
本文介绍了如何将Firestore时间戳打印为格式化的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时间戳在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())]);


....

抛出的错误是


无效的日期格式。

Invalid date format.

我是预期输出为:'2019年1月17日,下午2:19'

推荐答案

当我们将 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获取时间戳后将其转换回Datetime的方法:

Firestore的 timestamp 包含一个名为 toDate()的方法,该方法可以转换为String,然后将该String传递给 DateTime parse 方法转换回 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆