如何比较时间戳与颤动中的当前时间

How to compare timestamp to current time in flutter

这是我的时间戳 =“2020-05-29T17:43:39.622832+05:30”。我怎样才能将它传递给函数 readTimeStamp(它会给我一个不是 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;
}

这是我 return 3 天前和所有值的功能。

DateTime.parsereturns一个DateTimereadTimestamp 似乎期望自纪元以来的秒数,因此您只需要使用 DateTime.millisecondsSinceEpoch 并将毫秒转换为秒:

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

就个人而言,如果您控制 readTimestamp 函数,我会将其模棱两可的 timestamp 参数重命名为 secondsSinceEpoch 以明确它的期望。更好的方法是将其参数更改为直接采用 DateTime 而不是进行不必要的 DateTime <=> 毫秒 <=> 秒转换。

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