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(); } 
0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 - the question was why the exception only happens for January. Do you feel I haven't answered that?
I did not question that.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.