How to compare two dates that are constructed differently in Dart?
How to compare two dates that are constructed differently in Dart?
Here's how you can compare two dates that are constructed differently in Dart:
In Dart, you can compare dates using the compareTo() method or the comparison operators (<, >, <=, >=, ==). Here's how to compare dates constructed differently:
DateTime objectsIf both dates are represented as DateTime objects, you can directly compare them using the comparison operators or the compareTo() method:
DateTime date1 = DateTime(2023, 5, 21);
DateTime date2 = DateTime.now();
if (date1.compareTo(date2) < 0) {
print('date1 is before date2');
} else if (date1.compareTo(date2) > 0) {
print('date1 is after date2');
} else {
print('date1 is the same as date2');
}
If one date is represented as a String or a different format, you'll need to parse it into a DateTime object before comparing:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.