Search code examples
javaandroidkotlindatetimepicker

App crashes on using DateTime picker - Invalid value for MonthOfYear (valid values 1 - 12): 0


I have been using the DateTime picker without any issue for my Kotlin based android app, until it was bought to my notice that on using the DateTime picker the app is crashing. On further testing I relaised it is primarily crashing for the month of January with the below error being highlighted. I tried by moving from Java 1.8 to 1.7 but then i loose other functionalities in the app... any suggestions on how I can overcome this issue? This seems to be a know issue but I am not able to find a cause/proper solution

The app crashes on getting YearMonth from the calendar

            val currentMonth = YearMonth.of(
                calendar.get(java.util.Calendar.YEAR),
                calendar.get(java.util.Calendar.MONTH)
            )

Fatal Exception: java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 0
   at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:311)
   at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:730)
   at java.time.YearMonth.of(YearMonth.java:221)
   at in.latom.latom.MainActivity.onCreate$lambda-11$lambda-10(MainActivity.kt:505)
   at in.latom.latom.MainActivity.$r8$lambda$fB3ERyY00fXDUSdrgD0tpQQiN-Y()
   at in.latom.latom.MainActivity$$ExternalSyntheticLambda11.onDateSet(:8)
   at android.app.DatePickerDialog.onClick(DatePickerDialog.java:173)
   at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:188)
   at android.os.Handler.dispatchMessage(Handler.java:106)
   at android.os.Looper.loop(Looper.java:246)
   at android.app.ActivityThread.main(ActivityThread.java:8595)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)

Solution

  • I would use LocalDateTime. For example val month = LocalDateTime.now().getMonth() or val month = LocalDateTime.now().getMonthValue() which returns the month as an int from 1 to 12

    ref: https://developer.android.com/reference/kotlin/java/time/LocalDateTime