简体   繁体   English

如何比较两个日历日期?

[英]How can I compare two Calendar dates?

I have a Java problem where I need to check if an item has expired. 我有一个Java问题,需要检查某项是否已过期。 This is supposed to check if the item is at least x (x is an integer and can be set to any integer value) months old. 这应该检查项目是否至少存在x(x是整数,可以设置为任何整数值)个月。

Just to reclarify Supposing I have a pack of eggs, I want to check if it has been 1 months since I added them ( dateAdded ). 只是为了澄清一下,假设我有一包鸡蛋,我想检查一下自添加dateAddeddateAdded )到现在已经有1个月了。

I wrote a simple comparison but it doesn't seem to give the correct response. 我写了一个简单的比较,但似乎没有给出正确的答案。 Here is the code. 这是代码。

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

The value of end of line is an integer 12 ie 12 months. 行尾的值是12的整数,即12个月。

我的脑子里没有javadoc,但是遵循以下原则:

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

Here's some similar example code, but using the Joda-Time 2.3 library. 这是一些类似的示例代码,但使用的是Joda-Time 2.3库。

FYI: 仅供参考:

  • A Joda-Time DateTime instance knows its own time zone. Joda-Time DateTime实例知道其自己的时区。
  • The minusMonths method is smart, handles Daylight Saving Time and other issues. minusMonths方法很聪明,可以处理minusMonths 时制和其他问题。 You may want to read its source code to verify its logic follows your business rules as to what "x number of months ago" means. 您可能需要阅读其源代码,以验证其逻辑是否符合您的业务规则中“ 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 );

Dump to console… 转储到控制台...

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

When run… 运行时...

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

as mentioned in the Calendar docs You should not rely on the number returned by compareTo - you just know that if it is greater than 0 that the original date is greater. 正如Calendar docs中提到的那样,您不应该依赖compareTo返回的数字-您只知道如果原始数字大于0,则原始日期会更大。

So create a new date (x months in the passed) and compare to that one. 因此,创建一个新日期(经过的x个月)并与该日期进行比较。

The method returns 0 if the time represented by the argument is equal to the time represented by this Calendar object; 如果参数表示的时间等于此Calendar对象表示的时间,则该方法返回0;否则,方法返回0。 or a value less than 0 if the time of this Calendar is before the time represented by the argument; 或小于0的值(如果此Calendar的时间早于参数表示的时间); or a value greater than 0 if the time of this Calendar is after the time represented. 或大于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);

       }
    }

Here is the working solution. 这是有效的解决方案。 Tested with JUNIT to confirm results. 经JUNIT测试以确认结果。

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

I subtracted the END_OF_LINE from today using the add method. 我使用add方法从今天减去了END_OF_LINE Notice the minus on line 3. I then compared to see if it is greater than 0. Thanks for all your suggestions. 注意第3行的负号。然后,我进行了比较,看它是否大于0。感谢您的所有建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM