Is there a better way to compare a date against another?

杀马特。学长 韩版系。学妹 提交于 2021-01-29 13:12:16

问题


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?


回答1:


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 DateTimes to have the same "date" and convert both to a common time zone (possibly UTC).




回答2:


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




回答3:


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! :)



来源:https://stackoverflow.com/questions/61314289/is-there-a-better-way-to-compare-a-date-against-another

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