Reputation: 265
My code is:
for (var rt in list) {
if (rt.date.day == date2.day &&
rt.date.month == date2.month &&
rt.date.year == date2.year) {
...
}
}
Is there a better way to compare a date against another?
Upvotes: 0
Views: 208
Reputation: 90025
You can make a helper function to strip off the time:
DateTime dateOnly(DateTime dateTime) => DateTime(dateTime.year, dateTime.month, dateTime.day);
and then you can use DateTime
's normal operator ==
:
if (dateOnly(rt.date) == dateOnly(date2)) {
...
}
Note that the above example assumes both dates are in the same time zone. If they might be in different time zones, you should precisely define what it means for two DateTime
s to have the same "date" and convert both to a common time zone (possibly UTC).
Upvotes: 1
Reputation: 495
Use difference
:
for (var rt in list) {
if (rt.date.difference(date2).inDays == 0) {
...
}
}
Documentation link: https://api.flutter.dev/flutter/dart-core/DateTime/difference.html
Upvotes: 1
Reputation: 1023
You could check the difference between the two dates (date.difference(otherDate)
, I think) and check that the difference between those two is miniscule, which in your context might make them "equal"
But yeah, turns out date-comparisons can be a bit fiddly! :)
Upvotes: 0