Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime comparison in dart

Tags:

flutter

dart

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 ?

like image 900
Mike O. Avatar asked Jun 15 '19 20:06

Mike O.


People also ask

How do you compare two DateTime darts?

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].

How do you know if a date is greater than today in flutter?

if (date(DateTime. now()). difference(date(lastDailyCheck)). inHours > 0) { // "One day" after. }


1 Answers

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.

like image 184
Julio Henrique Bitencourt Avatar answered Sep 27 '22 22:09

Julio Henrique Bitencourt