0

what does this error mean?

Exception in thread "AWT-EventQueue-0" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 0

It only happens for the month of January

this is my line of code

public int computeAge(Date birthDay) throws ParseException {
        LocalDate birthdate = LocalDate.of(birthDay.getYear(), birthDay.getMonth(), birthDay.getDay());
        LocalDate curDate = LocalDate.now();
        Period p = Period.between(birthdate, curDate);
        return p.getYears();
    }
Dory
  • 11
  • 2

1 Answers1

2

This happens because Date uses month numbers from 0 to 11, but LocalDate uses month numbers from 1 to 12. So even if your program doesn't throw the DateTimeException, it won't give you the correct result.

Please stop using the Date class, and just use classes from the java.time package instead. Those particular methods - getDay(), getMonth() and getYear() were deprecated last century, if I recall correctly.

In this case, you should use LocalDate instead of Date, because it expresses a combination of year, month and day, with no time component.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • Please do not suggest "stop using Date" as a solution as it is not a solution when 3rd party APIs require you to use them. Especially here as the author is clearly aware of LocalDate existing. The solution to the problem is to provide the correct way to convert Date to LocalDate (possibly in the form of linking to a duplicate question) and to recommend discarding Date if possible. – Torben Jun 01 '22 at 05:36
  • @Torben - the question was why the exception only happens for January. Do you feel I haven't answered that? – Dawood ibn Kareem Jun 01 '22 at 05:43
  • I did not question that. – Torben Jun 01 '22 at 07:48
  • @Torben IMO the *first* goal and therefore also the first piece of advice should be *get rid of `Date`*. As a secondary piece we can well add *in case you cannot do that, convert* (which, as you said, was exactly what OP was trying). And yes, unfortunately there are still very many situations where we interact with legacy code and cannot readily avoid `Date`. – Ole V.V. Jun 01 '22 at 09:31