My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000)
in a Flutter Firestore snapshot.
I want to print it as properly formatted date and
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())
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)
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);
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
.
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
Do like so:
DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]