如何从 2 个日期中获取最新的日期时间 |扑

How to get the latest date time from the 2 dates | Flutter

我有 2 个约会对象。我想从这 2 个日期中获取最新日期。 例如,第一个日期和时间是“2021-07-14 11:13:02”,第二个是“2021-04-25 10:24:08”。从这些我想找到最新的日期。我怎样才能在 Flutter 和 Dart 中得到这个。

您可以使用 DateTime.parse 和 isAfter(), isBefore() 方法。

void main()  {

  print(getLatestDate('2021-07-14 11:13:02', '2021-04-25 10:24:08'));
}

DateTime getLatestDate(String a, String b) {
  DateTime dateA = DateTime.parse(a);
  DateTime dateB = DateTime.parse(b);
  
  if (dateA.isBefore(dateB)) {
    return dateB; // If you want String, return b
  } else {
  return dateA; // If you want String, return a
  }
}