【问题标题】:How can I compare two Calendar dates?如何比较两个日历日期?
【发布时间】:2014-01-08 12:45:50
【问题描述】:

我有一个 Java 问题,我需要检查项目是否已过期。这应该检查项目是否至少存在 x 个月(x 是一个整数,可以设置为任何整数值)个月。

再次澄清假设我有一包鸡蛋,我想检查我添加它们是否已经 1 个月 (dateAdded)。

我写了一个简单的比较,但它似乎没有给出正确的响应。这是代码。

public Boolean isEndOfLine() {
    Calendar today = Calendar.getInstance();
    if(today.compareTo(dateAdded) >= END_OF_LINE) {
        return true;
    } else {
        return false;
    }
}

行尾的值是一个整数12,即12个月。

【问题讨论】:

  • 可以简化:return today.compareTo(dateAdded) >= END_OF_LINE;
  • joda.org/joda-time - 一个很好的库,用于处理 Java 中的日期和时间。比使用日历和日期更好。 stackoverflow.com/questions/13764106/…
  • END_OF_LINE 是什么? compareTo 返回 -1、0 或 1...
  • 您必须首先指定您实际要检查的内容。 “超过 x 个月”是一个口语条件,不能用任何编程语言精确表达。你认为一个月是 28、29、30 还是 31 天?你想考虑一天中的时间吗?如果是这样,您是否必须考虑像 DST 这样的时区变化?
  • END_OF_LINE 是一个整数,指定要比较的月份数

标签: java date calendar comparison


【解决方案1】:

我的脑海中没有javadoc,而是按照以下思路:

dateAdded.add(Calendar.Month, END_OF_LINE).compareTo(today) > 0

【讨论】:

  • 我赞成,因为这将关于 END_OF_LINE 的 OP 声明/评论视为过去几个月的整数跟踪,尽管我不太确定是否应该将 END_OF_LINE 添加到今天。但问题不是很清楚。请注意,compareTo() 在这里只是一个即时比较,所以这对于特定问题是可以的。
【解决方案2】:

这里有一些类似的示例代码,但使用的是Joda-Time 2.3 库。

仅供参考:

  • Joda-Time DateTime 实例知道自己的时区。
  • minusMonths 方法很聪明,可以处理Daylight Saving Time 和其他问题。您可能需要阅读其源代码以验证其逻辑是否符合您的业务规则,即“x 个月前”的含义。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

// Better to specify a time zone explicitly rather than rely on default.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html  (not quite up-to-date, read page for details)
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );

int countMonths = 2;

DateTime now = new DateTime( timeZone );
// If you want to include the entire day, get first moment of the day by calling "withTimeAtStartOfDay".
DateTime someMonthsAgo = now.minusMonths( countMonths ).withTimeAtStartOfDay();
DateTime dateAdded = new DateTime( 2013, 5, 6, 7, 8, 9, timeZone  ); // Arbitrary values for example.

// If 'dateAdded' happened prior to our target date-time 'someMonthsAgo', the pack of eggs is expired.
Boolean isEndOfLine = dateAdded.isBefore( someMonthsAgo );

转储到控制台...

System.out.println( "now: " + now );
System.out.println( "someMonthsAgo: " + someMonthsAgo );
System.out.println( "dateAdded: " + dateAdded );
System.out.println( "isEndOfLine: " + isEndOfLine );

运行时……

now: 2014-01-08T21:36:11.179+01:00
someMonthsAgo: 2013-11-08T00:00:00.000+01:00
dateAdded: 2013-05-06T07:08:09.000+02:00
isEndOfLine: true

【讨论】:

    【解决方案3】:

    Calendar docs 中所述 您不应该依赖 compareTo 返回的数字 - 您只知道如果它大于 0,则原始日期更大。

    所以创建一个新日期(过去的 x 个月)并与那个日期进行比较。

    【讨论】:

      【解决方案4】:

      如果参数表示的时间等于此 Calendar 对象表示的时间,则该方法返回 0;如果此日历的时间在参数表示的时间之前,则值小于 0;或大于 0 的值,如果此日历的时间晚于所表示的时间。

          import java.util.*;
      
          public class CalendarDemo {
      
             public static void main(String[] args) {
      
                // create two calendar at the different dates
                Calendar cal1 = new GregorianCalendar(2015, 8, 15);
                Calendar cal2 = new GregorianCalendar(2008, 1, 02);
      
                // compare the time values represented by two calendar objects.
                int i = cal1.compareTo(cal2);
      
                // return positive value if equals else return negative value
                System.out.println("The result is :"+i);
      
                // compare again but with the two calendars swapped
                int j = cal2.compareTo(cal);
      
                // return positive value if equals else return negative value
                System.out.println("The result is :" + j);
      
             }
          }
      

      【讨论】:

        【解决方案5】:

        这是有效的解决方案。使用 JUNIT 进行测试以确认结果。

        public Boolean isEndOfLine() {
            Calendar today = Calendar.getInstance();
            today.add(Calendar.MONTH, -END_OF_LINE);
            return today.compareTo(dateAdded) >= 0;
        }
        

        我使用 add 方法从今天减去 END_OF_LINE。注意第 3 行的减号。然后我比较了它是否大于 0。感谢您的所有建议。

        【讨论】:

          猜你喜欢
          • 2011-01-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-26
          相关资源
          最近更新 更多