kotlinx-datetime icon indicating copy to clipboard operation
kotlinx-datetime copied to clipboard

Getting days in Month

Open Tommyten opened this issue 3 years ago • 6 comments

Is there currently any way of getting the number of total days in a month?

Tommyten avatar Feb 03 '22 08:02 Tommyten

It's dependent on the year, due to leap days, so something like this is needed:

fun monthDays(year: Int, month: Month): Int {
  val start = LocalDate(year, month, 1)
  val end = start.plus(DateTimeUnit.MONTH)
  return start.until(end, DateTimeUnit.DAY)
}

Literally, "how many days between the start of this month and the next month".

dkhalanskyjb avatar Feb 03 '22 08:02 dkhalanskyjb

Thanks for the suggestion. I think having this method implemented in the library would prove useful to quite a lot of people.

Tommyten avatar Feb 04 '22 06:02 Tommyten

Perhaps if we get that YearMonth from #168, we could do something like YearMonth.of(22, 2).lengthOfMonth() (java.time). @dkhalanskyjb Would you consider a PR if I (or someone) happened to cover most if not all methods from java.time.YearMonth? I think a lot of people would find this helpful.

imashnake0 avatar Feb 15 '22 22:02 imashnake0

There's an upside to the solution provided above: it uses the conceptually simple until function that calculates the length of some time segments and can be used in various other ways: it allows one to learn the number of days in a given year, or the number of minutes in a given day (which may vary due to DST transitions), or the number of seconds in a year…

By not providing wrappers around until for these cases, we direct the users of the library to learn to wield the flexibility of until. If getting the number of days in a month is something that's very commonly needed, then, true, it does make sense to provide this convenience wrapper, but it's not yet clear that it is.

dkhalanskyjb avatar Feb 16 '22 07:02 dkhalanskyjb

IMO, getting the length of a month by creating two dates and subtracting them is a more contrived way than to query it directly from some calendar info provider. So, these functions are conceptually not wrappers around until, but on the opposite, until can be considered to use this low level info about the calendar which we have internally but do not expose because we haven't yet found the right API form for that.

ilya-g avatar Feb 16 '22 12:02 ilya-g

If we did have a calendar-info-provider thing, then sure. Currently, however, the until and periodUntil functions are the ways to access this functionality.

My point is, providing just something like fun daysInMonth(month: Month, year: Int): Int would be sacrificing orthogonality and conceptual clarity, as the result is not a property of a year or a month.

Implementing a more general way to query calendar info would be a clear solution for this, I agree. So would be something like YearMonth.lengthInDays if we did have YearMonth.

dkhalanskyjb avatar Feb 16 '22 12:02 dkhalanskyjb