Is there a multiplatform calendar library, or new functionality in kotlinx.datetime to get number of days in a month?

I have code that could benefit from knowing how many days a given month has. This is not as trivial as it may sound; every 4 years, February has 29 days instead of 28 for example. And throughout history, there have been unusual years with slightly different days per month. (This is one example for why you should never write your own datetime / calendar code, and instead use existing libraries.)

kotlinx.datetime has great functionality for local datetime timestamps, timezones etc. but I did not find anything for this problem. Iā€™d like to use something multiplatform-compatible if possible.


1 Like

You cannot determine this without referencing the year and the month. The way to pair a year with a month in kotlinx.datetime is as a local date. So to compute it you could construct a Local date for the first day of the given month and year, then create a second local date by adding 1 month to it, then getting the difference in days.

But there is also Klock which is another KMM date library and it has a YearMonth type that encompasses just the combination of year and month that will give you what you want.

There are tradeoffs between the two libraries and our application actually used both.