JsonConverter for firestore timestamp
1 min read

JsonConverter for firestore timestamp

In firestore, timestamp represents UTC epoch time in nanoseconds resolution. It could be easily converted to a flutter DateTime object using the toDate method. Similarly, a Flutter DateTime object could be converted to a Timestamp using the fromDate static method.

So, a JsonConverter could be created easily as follows

class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
  const TimestampConverter();

  @override
  DateTime fromJson(Timestamp timestamp) {
    return timestamp.toDate();
  }

  @override
  Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
}