krushi21
krushi21

Reputation: 125

How to compare timestamp to current time in flutter

This is my timestamp = "2020-05-29T17:43:39.622832+05:30". How can I pass it to a function readTimeStamp (it will give me error of not type of int)?

date = DateTime.parse(bookDetails.timestamp);
   print(readTimestamp(date));

String readTimestamp(int timestamp) {
  var now = DateTime.now();
  var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
  var diff = now.difference(date);
  String time = '';

  if (diff.inSeconds <= 0 ||
      diff.inSeconds > 0 && diff.inMinutes == 0 ||
      diff.inMinutes > 0 && diff.inHours == 0 ||
      diff.inHours > 0 && diff.inDays == 0) {
  } 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;
}

This is my function to return value like 3 day ago and all.

Upvotes: 5

Views: 8365

Answers (2)

Zoul Barizi
Zoul Barizi

Reputation: 530

bool isAfterToday(Timestamp timestamp) {
    return DateTime.now().toUtc().isAfter(
        DateTime.fromMillisecondsSinceEpoch(
            timestamp.millisecondsSinceEpoch,
            isUtc: false,
        ).toUtc(),
    );
}

Upvotes: 2

jamesdlin
jamesdlin

Reputation: 90015

DateTime.parse returns a DateTime. readTimestamp appears to expect the number of seconds since the epoch, so you just need to use DateTime.millisecondsSinceEpoch and convert milliseconds to seconds:

print(readTimestamp(date.millisecondsSinceEpoch ~/ 1000));

Personally, if you control the readTimestamp function, I would rename its ambiguous timestamp argument to secondsSinceEpoch to make it clear what it expects. Even better would be to change its argument to take a DateTime directly instead of doing unnecessary DateTime <=> milliseconds <=> seconds conversions.

Upvotes: 4

Related Questions