有没有更好的方法可以将日期与另一个日期进行比较? [英] Is there a better way to compare a date against another?

查看:60
本文介绍了有没有更好的方法可以将日期与另一个日期进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

  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?

推荐答案

您可以创建一个辅助函数来节省时间:

You can make a helper function to strip off the time:

DateTime dateOnly(DateTime dateTime) => DateTime(dateTime.year, dateTime.month, dateTime.day);

,然后您可以使用 DateTime 的常规 operator == :

and then you can use DateTime's normal operator ==:

if (dateOnly(rt.date) == dateOnly(date2)) {
  ...
}

请注意,上面的示例假定两个日期都在相同的时区中.如果它们可能位于不同的时区,则应精确定义两个 DateTime 具有相同的日期"的含义,然后将两者都转换为相同的时区(可能是UTC).

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).

这篇关于有没有更好的方法可以将日期与另一个日期进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆