DateTime comparison in dart

泪湿孤枕 提交于 2021-01-26 12:18:47

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/56613875/datetime-comparison-in-dart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!