43

I am trying to sort list of DateTime time elements in ascending order.I have realized normal operators like > or < don't cut it. What is the best way to compare two DateTime variables ?

3 Answers 3

76

Simply use the methods isAfter(), isBefore() or isAtSameMomentAs() from DateTime.

Other alternative, use compareTo(DateTime other), as in the docs:

Compares this DateTime object to [other], returning zero if the values are equal.

Returns a negative value if this DateTime [isBefore] [other]. It returns 0 if it [isAtSameMomentAs] [other], and returns a positive value otherwise (when this [isAfter] [other]).

Here a code example of sorting dates:

void main() {
  var list = [
    DateTime.now().add(Duration(days: 3)),
    DateTime.now().add(Duration(days: 2)),
    DateTime.now(),
    DateTime.now().subtract(Duration(days: 1))
  ];

  list.sort((a, b) => a.compareTo(b));
  print(list);
}

See it working here.

1
  • how can I compare 2 dates & time? Kindly share your suggestion. Thanks.
    – Kamlesh
    Jun 11, 2021 at 17:00
11

This is I how understood and implemented the code it will result in true / false in boolean mode.

DateTime valEnd = edate ;
DateTime date =DateTime.now();
bool valDate = date.isBefore(valEnd);
3

DateTime comparison in dart

DateTime.compareTo(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.compareTo(dt2) == 0){
    print("Both date time are at same moment.");
}

if(dt1.compareTo(dt2) < 0){
    print("DT1 is before DT2");
}

if(dt1.compareTo(dt2) > 0){
    print("DT1 is after DT2");
}

DateTime.isAtSameMomentAs(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isAtSameMomentAs(dt2)){
   print("Both DateTime are at same moment.");
}

DateTime.isAfter(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isAfter(dt2)){
   print("DT1 is after DT2");
}

DateTime.isBefore(DateTime other):

DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");

if(dt1.isBefore(dt2)){
   print("DT1 is before DT2");
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.