如何将 Firestore 时间戳打印为格式化的日期和时间

ary*_*ngh 24 time dart flutter google-cloud-firestore

我的时间戳Timestamp(seconds=1560523991, nanoseconds=286000000)在 Flutter Firestore 快照中返回。

我想将其打印为格式正确的日期和时间。

DateTime.now()在创建新记录并使用 Firestore 快照检索它时使用将当前 DateTime 存储在 Firestore 中,但我无法转换为格式化的日期时间。我正在使用 libintl.dart进行格式化。

保存数据的代码

       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())]);


....
Run Code Online (Sandbox Code Playgroud)

抛出的错误是

日期格式无效。

我期待输出是: 'Jan 17, 2019, 2:19 PM'

小智 30

当我们将DateTime对象推送到 Firestore 时,它​​会在内部将其转换为它自己的时间戳对象并存储它。

从 Firestore 获取时间戳后将其转换回日期时间的方法:

Firestore 的时间戳包含一个名为toDate()的方法,该方法可以转换为 String,然后可以将该 String 传递给DateTimeparse方法以转换回DateTime

DateTime.parse(timestamp.toDate().toString())
Run Code Online (Sandbox Code Playgroud)

  • 我认为我们首先不需要将 timestamp.toDate() 转换为字符串,然后解析该字符串以获取实际的 DateTime。你可以简单地执行timestamp.toDate()。它已经返回日期时间。 (5认同)

小智 15

这是方法!

Firestore 将像 Timestamp(seconds=1560523991, nanoseconds=286000000) 一样返回 TimeStamp。

这可以解析为

Timestamp t = document['timeFieldName'];
DateTime d = t.toDate();
print(d.toString()); //2019-12-28 18:48:48.364
Run Code Online (Sandbox Code Playgroud)


Ash*_*ngh 8

您可以像这样直接将 Firestore 时间戳对象转换为 DateTime:

DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate();
Run Code Online (Sandbox Code Playgroud)

这将以 dart 的 DateTime 格式返回您的 Firestore 时间戳。为了转换您的DateTime对象,您可以使用intl包中的DateFormat类。您可以使用您获得的 DateTime 对象来获取您选择的格式,如下所示:

DateFormat.yMMMd().add_jm().format(myDateTime);
Run Code Online (Sandbox Code Playgroud)

此代码产生如下输出:

Apr 21, 2020 5:33 PM
Run Code Online (Sandbox Code Playgroud)


Shy*_*hil 5

时间戳参数是以秒为单位的时间

String formatTimestamp(int timestamp) {
      var format = new DateFormat('d MMM, hh:mm a');
      var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
      return format.format(date);
    }
Run Code Online (Sandbox Code Playgroud)

请检查答案以了解国际日期格式

希望能帮助到你 !


小智 1

即使您向 firestore 发送 DateTime,您也会从 firestore 获得 unix 时间戳。

您可以使用以下命令解析 Firestore 中的 DateTimeDateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

DateTime 类有两个返回字符串的选项。toIso8601String()toString() 选择您需要的一个。或者使用例如。DateTime.now().hour; 获取我们的并创建您自己的输出。

有关更多信息:检查https://api.dartlang.org/stable/2.4.0/dart-core/DateTime-class.html