1

In my groovy test case below i have certain date objects which later i am formatting using DateUtil.format(calendarObj,"yyyy-MM-dd"). But when i print the result, it increments the month by 1.

For Example:

Groovy Code:

def testDate=new GregorianCalendar(2000,1,30);
def testDate1=new GregorianCalendar(2000,1,5);
def testDate2=new GregorianCalendar(2000,4,25);
def testDate3=new GregorianCalendar(2000,6,10);

Output (using System.out.println(DateUtil.format(testDate/1/2/3,"yyyy-MM-dd"))):

2000-03-01
2000-02-05
2000-05-25
2000-07-10

Can anyone please explain why this is happening.

Héctor
  • 24,444
  • 35
  • 132
  • 243
user9148262
  • 63
  • 1
  • 8
  • Curiously, in the first example you are creating the `February 30th` (it doesn't exist) and in the formatting you are getting `March 1st`. – Héctor Dec 28 '17 at 08:08
  • 1
    @Hector: Not that curious at all. 2000 was a leap year were february had 29 days. So by setting the value to 30-february the calendar will automatically change the month to march and day to 1. In the same way that setting it to 32-january would result in a date that actually is the 1. february. – OH GOD SPIDERS Dec 28 '17 at 08:49
  • 1
    That's a really bad design for me. What do you think? – Héctor Dec 28 '17 at 08:52
  • 1
    You are using troublesome old date-time classes that were supplanted years ago by the *java.time* classes built into Java 8 and later. – Basil Bourque Dec 28 '17 at 09:05
  • 2
    Related: [Why is January month 0 in Java Calendar?](https://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar) – Ole V.V. Dec 28 '17 at 09:08
  • The good solution is to use `java.time` (as mentioned) and `LocalDate.of(2000, Month.JANUARY, 30)`, etc. – Ole V.V. Dec 28 '17 at 09:11

1 Answers1

5

Months in Java (and by extension Groovy) are zero-based, so January is 0, February is 1, etc.

As noted in the comments, this is only the case for the original Java date/time classes (java.util.Date, java.util.Calendar, ...).

For classes in the (preferred) new date/time API that was introduced in Java 8 (java.time.LocalDate, ...), this behavior was changed to be more intuitive.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156