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?
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.
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.
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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With