3

I have the following code to get the last day of the month but what is strange is that returns 31 for the last day. On that month of the year there should be only 30 days. Therefore, when I tried to parse the string data, I get Caused by: java.text.ParseException: Unparseable date: "2020/6/31 00:00:00" Some tips or example will be lovely. I would love to hear from you!

val cal: Calendar = Calendar.getInstance().also {
            it.clear()
            it.set(Calendar.YEAR, 2020)
            it.set(Calendar.MONTH, 6)
        }
        val lastDaysOfMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
Nancy
  • 129
  • 2
  • 13
  • 5
    [`January`](https://docs.oracle.com/javase/7/docs/api/constant-values.html#java.util.Calendar.JANUARY) is `0`. `Calendar.MONTH` of `6` is [July](https://docs.oracle.com/javase/7/docs/api/constant-values.html#java.util.Calendar.JULY). And there **are** 31 days in July 2020. Don't use the `Calendar` class if you can avoid it. The `java.time` API is far more consistent. If you can't avoid using `Calendar`, use the provided constants - `it.set(Calendar.MONTH, Calendar.JUNE)` – Elliott Frisch Aug 02 '19 at 03:35
  • My android app's min sdk is 16 ....... – Nancy Aug 02 '19 at 03:48
  • 3
    You can use a backport of Java time API. I would like to suggest [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) – Andrei Tanana Aug 02 '19 at 07:28
  • @ElliottFrisch, you could make that an answer. – gidds Aug 02 '19 at 08:16

1 Answers1

1

The java.util.Calendar class is notoriously difficult to use, so much so that Joda-Time was independently developed and then officially adapted/adopted into the java.time package (with some small modifications from the original developer). Here, the problem you have with Calendar is that JANUARY is a constant 0. So, when you use a 6 for Calendar.MONTH that is JULY. There are 31 days in July 2020. Don't use the Calendar class if you can avoid it. The java.time API is far more consistent. If you can't avoid using Calendar, use the provided constants - for example,

it.set(Calendar.MONTH, Calendar.JUNE)

But, even if you're using a platform without java.time, you can almost certainly use the ThreeTen-Backport (or the Android version) like,

val lastDaysOfMonth = java.time.LocalDate.of(2020, 6, 1)
        .with(java.time.temporal.TemporalAdjusters.lastDayOfMonth())
        .getDayOfMonth();

That would be a lot shorter with import statements (naturally).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Yes, you can use the backport of java.time on Android API level 16. See [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project) for a thorough explanation. – Ole V.V. Aug 04 '19 at 07:16