Dart中的DateTime比较 [英] DateTime comparison in dart
问题描述
我正在尝试按升序对DateTime时间元素列表进行排序.我已经实现了>或<等常规运算符.不要切.比较两个DateTime变量的最佳方法是什么?
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 ?
推荐答案
只需使用方法 isAfter()
, isBefore()
或 isAtSameMomentAs()
来自 DateTime
.
Simply use the methods isAfter()
, isBefore()
or isAtSameMomentAs()
from DateTime
.
其他替代方法,如文档中所述,使用 compareTo(DateTime other)
:
Other alternative, use compareTo(DateTime other)
, as in the docs:
将此DateTime对象与[other]进行比较,如果值相等,则返回零.
Compares this DateTime object to [other], returning zero if the values are equal.
如果此DateTime [isBefore] [other]返回一个负值.返回0如果它是[isAtSameMomentAs] [other],则返回正值;否则(当此[isAfter] [other]时).
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);
}
此处.
这篇关于Dart中的DateTime比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!