简体   繁体   中英

How can I compare two Calendar dates?

I have a Java problem where I need to check if an item has expired. 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.

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

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.

我的脑子里没有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.

FYI:

  • A Joda-Time DateTime instance knows its own time zone.
  • The minusMonths method is smart, handles Daylight Saving Time and other issues. 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.
// © 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.

So create a new date (x months in the passed) and compare to that one.

The method returns 0 if the time represented by the argument is equal to the time represented by this Calendar object; or a value less than 0 if the time of this Calendar is before the time represented by the argument; or a value greater than 0 if the time of this Calendar is after the time represented.

    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.

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. Notice the minus on line 3. I then compared to see if it is greater than 0. Thanks for all your suggestions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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