How to compare two dates that are...
How to compare two dates that are...
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:
String dateString = '2023-05-21';
DateTime parsedDate = DateTime.parse(dateString);
DateTime currentDate = DateTime.now();
if (parsedDate.compareTo(currentDate) < 0) {
print('parse...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào