【问题标题】:How to check if there is at least 1 day difference between 2 dates如何检查2个日期之间是否至少相差1天
【发布时间】:2013-08-07 10:20:41
【问题描述】:

所以,我必须检查 2 个日期之间的差异是否至少为 1 天。那么方法应该返回true,否则为false。

我使用的日期格式是GregorianCalendar(year, month, day)

所以我已经有一个使用date1.before(date2)的方法,但它也检查时间,所以如果date1date2之前它返回true,即使它们是同一天(但时间不同! )。

我需要一种方法来检查日期之间的差异是否至少为 1 天。

有什么想法吗?

【问题讨论】:

    标签: java date compare gregorian-calendar


    【解决方案1】:

    你可以这样使用:

    public boolean dateDifference(Date d1, Date d2)
    { 
    long currentDateMilliSec = d1.getTime();
    long updateDateMilliSec = d2.getTime();
    long diffDays = (currentDateMilliSec - updateDateMilliSec) / (24 * 60 * 60 * 1000);
    if (diffDays >= 1) return true;
    else return false;
    }
    

    【讨论】:

      【解决方案2】:

      cal1 加 1 天,测试是否不在 cal2 之后

          cal1.add(Calendar.DATE, 1);
          System.out.println(!cal1.after(cal2));
      

      【讨论】:

      • 在此之前您还需要检查cal1.before(cal2) == true
      猜你喜欢
      • 2021-05-17
      • 1970-01-01
      • 2015-07-01
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 2020-03-06
      相关资源
      最近更新 更多