简体   繁体   中英

Java Calendar Comparison methods not returning proper results

I'm currently having very odd behavior when doing comparisons on calendar objects.

I have a method that is to determine if the current date asOfDate is after 31-DEC-13 lastDayOfDec13 . The asOfDate = 09-JAN-14. I've used similar comparison methods before but I'm not sure why this isn't working at all.

09-JAN-14 is definitely after 31-DEC-13 but it is returning false.

My code is below:

private Boolean isTodayAfterDec2013() throws Exception {
    Calendar asOfDate = getAsOfDate();

    Calendar lastDayOfDec13 = getAsOfDate();
    lastDayOfDec13.set(Calendar.YEAR, 2013);
    lastDayOfDec13.set(Calendar.MONTH, Calendar.DECEMBER);
    lastDayOfDec13.set(Calendar.DAY_OF_MONTH, 31);

    System.out.println("lastDayOfDec13 "+CommonUtils.getDatebaseFormattedDate(lastDayOfDec13));
    System.out.println("asOfDate "+CommonUtils.getDatebaseFormattedDate(asOfDate));

    System.out.println("asOfDate.after(lastDayOfDec13) " + asOfDate.after(lastDayOfDec13));
    System.out.println("asOfDate.compareTo(lastDayOfDec13) " + asOfDate.compareTo(lastDayOfDec13));

    if(asOfDate.after(lastDayOfDec13)) {
        System.out.println("Today is after 31-DEC-13");
        return true;
    }
    return false;

}

And my console is printing:

lastDayOfDec13 31-DEC-13

asOfDate 09-JAN-14

asOfDate.after(lastDayOfDec13) false

asOfDate.compareTo(lastDayOfDec13) -1

Is there something about the calendar object that I don't understand? The year should be working fine. Also, my requirement is to use Calendar objects, I cannot use JODA or any outside libraries.

Any help would be greatly appreciated. Thanks.

Your function getAsOfDate() must be wrong...

public static void main(String[] args) {
  Calendar asOfDate = Calendar.getInstance();
  asOfDate.set(Calendar.YEAR, 2014);
  asOfDate.set(Calendar.MONTH, Calendar.JANUARY);
  asOfDate.set(Calendar.DAY_OF_MONTH, 9);

  Calendar lastDayOfDec13 = Calendar.getInstance();
  lastDayOfDec13.set(Calendar.YEAR, 2013);
  lastDayOfDec13.set(Calendar.MONTH, Calendar.DECEMBER);
  lastDayOfDec13.set(Calendar.DAY_OF_MONTH, 31);
  // System.out.println("lastDayOfDec13 "+CommonUtils.getDatebaseFormattedDate(lastDayOfDec13));
  // System.out.println("asOfDate "+CommonUtils.getDatebaseFormattedDate(asOfDate));

  System.out.println("asOfDate.after(lastDayOfDec13) " + asOfDate.after(lastDayOfDec13));
  System.out.println("asOfDate.compareTo(lastDayOfDec13) " + asOfDate.compareTo(lastDayOfDec13));

  if(asOfDate.after(lastDayOfDec13)) {
      System.out.println("Today is after 31-DEC-13");
  }
}

Outputs

asOfDate.after(lastDayOfDec13) true
asOfDate.compareTo(lastDayOfDec13) 1
Today is after 31-DEC-13

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