Wrong date/month from java.util.calendar

Wrong date/month from java.util.calendar

Tags
Java
Kotlin
Published
November 14, 2019
Author
Mateusz Teteruk
Do you use java.util.calendar and you have wrong date/month from it? I bet you encounter some problems regarding getting proper date, day or even month from calendar instance? Let’s get down to business.

Months indexing

This blog post is not about indexing of months in java.util.calendar. You shouldn’t be surprised that Java has inconsistent APIs. Calendar.MONTHS has indices from 0 to 11. More info can be found on StackOverflow or just reading docs. But I will not talk about it today.

Today is October and next month is December. Ooops?

I have to mention that this situation is very specific, can be encountered only in some scenarios, i.e. last day of October which has 31 days. Having proper date is crucial to reproduce getting wrong date/month from java.util.calendar.

Wrong date – example

Let’s assume that today is Halloween, 31 October 2019. Look at this situation:
{% highlight kotlin %} val calendar = Calendar.getInstance().apply { set(Calendar.MONTH, 9) set(Calendar.DAY_OF_MONTH, 31) } (calendar as GregorianCalendar).toZonedDateTime() // 31 Oct 2019 calendar.set(Calendar.MONTH, 10) // set month to Nov (calendar as GregorianCalendar).toZonedDateTime() // 1 Dec 2019 {% endhighlight %}
What the hell you may think? Why did I get 1st December? Wrong month, wrong day java.util.calendar what’s going on?! Yup, this is default behavior for this library. „But it’s wrong!!” – you may say. Let me explain.

Explanation

Getting instance from Calendar returns current date which is 31 October. That’s great. But what happens if we change month to the next one – November?
Well, November has only 30 days, so date „31 November 2019” is invalid. Java is „smart” hence in order to „fix” wrong date, date is incremented and we receive 1 December.
And that was the UI bug I encountered on 31 October in my job project 🙂 Have you any funny or scary histories with java.util.calendar or ThreeTenABP? Share it in comments below!