Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8223288

Gregorian calendar giving wrong result for add month [day of month > maxDayOfMo]

XMLWordPrintable

    • generic
    • generic

      A DESCRIPTION OF THE PROBLEM :
      Gregorian calendar is returning wrong result while adding months. For e.g. I was trying to add 4 months in 31st October 2018. org.joda.time.LocalDate returns 28th March 2019 whereas Gregorian calendar is returning 1st of March.

      So I took a deep dive inside the calendar code and found out that the "pinDayOfMonth" might be returning wrong result which is not expected. The documentation of the method says "After adjustments such as add(MONTH), add(YEAR), we don't want the month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar 3, we want it to go to Feb 28. Adjustments which might run into this problem call this method to retain the proper month.". So I went ahead and tested the same scenario as given in the documentation. The result I got was 1st March 2019 whereas the expected according to the method doc is 28th Feb 2019.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      1) Run the snippet provided below
      2) Java jdk version used is "jdk1.8.0_65".

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      Wed Feb 28 00:00:00 IST 2019
      ACTUAL -
      Thu Mar 01 00:00:00 IST 2018

      ---------- BEGIN SOURCE ----------
      public static void main(String[] args) {
          // .. add one month to the date
          Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
          cal.setTime(LocalDate.parse("2018-01-31").toDate());

          System.out.println("***************************************************************");
          System.out.println(cal.getTime()); // Expected: Wed Jan 31 00:00:00 IST 2018

          cal.add(Calendar.MONTH, 1);

          System.out.println(cal.getTime()); // Expected: Wed Feb 28 00:00:00 IST 2019
          System.out.println("***************************************************************");
        }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Change in "pinDayOfMonth" method of "java.util.GregorianCalendar" class:-
      - set(DAY_OF_MONTH, monthLen - 1) instead of set(DAY_OF_MONTH, monthLen).

      FREQUENCY : always


            naoto Naoto Sato
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: