Converting timestamp

Your timestamp format is in fact in Seconds (Unix timestamp) as opposed to microseconds. If so the answer is as follows:

Change:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);

to

var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

  • From milliseconds:

    var millis = 978296400000;
    var dt = DateTime.fromMillisecondsSinceEpoch(millis);
    
    // 12 Hour format:
    var d12 = DateFormat('MM/dd/yyyy, hh:mm a').format(dt); // 12/31/2000, 10:00 PM
    
    // 24 Hour format:
    var d24 = DateFormat('dd/MM/yyyy, HH:mm').format(dt); // 31/12/2000, 22:00
    
  • From Firestore:

    Map<String, dynamic> map = docSnapshot.data()!;
    DateTime dt = (map['timestamp'] as Timestamp).toDate();
    
  • Converting one format to other:

    • 12 Hour to 24 Hour:

      var input = DateFormat('MM/dd/yyyy, hh:mm a').parse('12/31/2000, 10:00 PM');
      var output = DateFormat('dd/MM/yyyy, HH:mm').format(input); // 31/12/2000, 22:00
      
    • 24 Hour to 12 Hour:

      var input = DateFormat('dd/MM/yyyy, HH:mm').parse('31/12/2000, 22:00');
      var output = DateFormat('MM/dd/yyyy, hh:mm a').format(input); // 12/31/2000, 10:00 PM
      

Use intl package (for formatting)


Full code for anyone who needs it:

String readTimestamp(int timestamp) {
    var now = DateTime.now();
    var format = DateFormat('HH:mm a');
    var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    var diff = now.difference(date);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else if (diff.inDays > 0 && diff.inDays < 7) {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + ' DAY AGO';
      } else {
        time = diff.inDays.toString() + ' DAYS AGO';
      }
    } else {
      if (diff.inDays == 7) {
        time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
      } else {

        time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
      }
    }

    return time;
  }

Thank you Alex Haslam for the help!


If you are using firestore (and not just storing the timestamp as a string) a date field in a document will return a Timestamp. The Timestamp object contains a toDate() method.

Using timeago you can create a relative time quite simply:

_ago(Timestamp t) {
  return timeago.format(t.toDate(), 'en_short');
}

build() {
  return  Text(_ago(document['mytimestamp'])));
}

Make sure to set _firestore.settings(timestampsInSnapshotsEnabled: true); to return a Timestamp instead of a Date object.


if anyone come here to convert firebase Timestamp here this will help

Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)