Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Firestore timestamp in Flutter

How to change the firestore timestamp to something like "2 days ago or 1 hour ago" ? I tried displaying it directly but the data that came out was a string like Timestamp(seconds=1556459022, nanosecond=0).

How to do that?

like image 894
anangfaturrohman Avatar asked May 03 '19 15:05

anangfaturrohman


People also ask

What is the format of firestore timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

How do you convert timestamp to time in flutter?

To get date time from a given timestamp, we can use the DateTime. fromMillisecondsSinceEpoch or DateTime. fromMicrosecondsSinceEpoch constructor. We have to multiply the timestamp input by 1000 because DateTime.


2 Answers

Firestore's timestamp has a toDate() method that will return a dart DateTime object.

From that you can use regular dart solutions, like DateFormat or the timeago library to display it as in:

timeago.format(firestoreTimestamp.toDate());
like image 65
Edman Avatar answered Oct 22 '22 00:10

Edman


This is how I worked it out. Import the following package:

import 'package:timeago/timeago.dart' as timeago;

Now, get the timestamp from Firestore. For example, for the field name 'timestamp', refer the following code:

final document = Firestore.instance.collection("yourCollectionName").snapshots();

Now Access your timestamp using the following:

`Timestamp timestamp = document['timestamp'];

Finally, display the result in the app. Example:

Text(timeago.format(DateTime.tryParse(timestamp.toDate().toString())).toString());
like image 36
Ron Avatar answered Oct 21 '22 23:10

Ron