anangfaturrohman
anangfaturrohman

Reputation: 441

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?

Upvotes: 9

Views: 12164

Answers (3)

You don't need to use a package for this. Already data comes from firebase in Timestamp type.

I think the type of the incoming data is Map<String, dynamic>.

So,for example,

Timestamp? lastseen = json['lastseen']

Also a suggestion for you; Don't forget to build models for this type of data. It will be easier for you to use. I shared an example user model with you.

List<LUser> UserFromJson(String str) => List<LUser>.from(json.decode(str).map((x) => LUser.fromJson(x)));

String UserToJson(List<LUser> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class LUser {
  LUser({
    this.uid,
    this.age,
    this.city,
    this.horoscope,
    this.job,
    this.mail,
    this.name,
    this.tel,
    this.username,
    this.lastseen,
    this.createdtime,
  });
  String? uid;
  String? age;
  String? city;
  String? horoscope;
  String? job;
  String? mail;
  String? name;
  String? tel;
  String? username;
  Timestamp? lastseen;
  Timestamp? createdtime;

  factory LUser.fromJson(Map<String, dynamic> json) {
    return LUser(
      uid: json["uid"],
      age: json["age"],
      city: json["city"],
      horoscope: json["horoscope"],
      job: json["job"],
      mail: json["mail"],
      name: json["name"],
      tel: json["tel"],
      username: json["username"],
      lastseen: json["lastseen"],
      createdtime: json["createdtime"],
    );
  }

  Map<String, dynamic> toJson() => {
        "uid": uid,
        "age": age,
        "city": city,
        "horoscope": horoscope,
        "job": job,
        "mail": mail,
        "name": name,
        "tel": tel,
        "username": username,
        "lastseen": lastseen,
        "createdtime": createdtime,
      };
}

Upvotes: 0

Ron
Ron

Reputation: 271

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

Upvotes: 9

Edman
Edman

Reputation: 5605

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

Upvotes: 19

Related Questions