How to print Firestore timestamp as formatted date and time

前端 未结 13 1577
野性不改
野性不改 2021-02-07 11:07

My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000) in a Flutter Firestore snapshot.

I want to print it as properly formatted date and

相关标签:
13条回答
  • 2021-02-07 11:58

    When we push the DateTime object to Firestore, it internally converts it to it's own timestamp object and stores it.

    Method to convert it back to Datetime after fetching timestamp from Firestore:

    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())
    
    0 讨论(0)
  • 2021-02-07 12:02

    Using cloud firestore, Here's my what worked for me:

    Text(snapshot.data["YouKey"].toDate().toString().substring(0,16))
    

    subString is optionnal, I've added it because I had the clock time with many number after the minute (like 12:00 00:00:00)

    0 讨论(0)
  • 2021-02-07 12:09

    You should use fromMillisecondsSinceEpoch function.

    var d = new DateTime.fromMillisecondsSinceEpoch(ts, isUtc: true);
    

    Here ts is int type.

    So we can convert Firebase timestamps to DateTime object as follows.

    DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp.seconds * 1000);
    
    0 讨论(0)
  • 2021-02-07 12:11

    I found Ashutosh's suggestion gives more user friendly output. A function like this is recommended in a helper class with a static method.

      static convertTimeStamp(Timestamp timestamp) {
        assert(timestamp != null);
        String convertedDate;
        convertedDate = DateFormat.yMMMd().add_jm().format(timestamp.toDate());
        return convertedDate;
      }
    

    Intl package is require for DateFormat.

    0 讨论(0)
  • 2021-02-07 12:12

    Here is way!

    Firestore will return TimeStamp like Timestamp(seconds=1560523991, nanoseconds=286000000).

    This can be parsed as

    Timestamp t = document['timeFieldName'];
    DateTime d = t.toDate();
    print(d.toString()); //2019-12-28 18:48:48.364
    
    0 讨论(0)
  • 2021-02-07 12:13

    Do like so:

    DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]
    
    0 讨论(0)
提交回复
热议问题