javadatetime

What's the best way to get the number of days in a month using the java.time API?


I need to determine the number of days in the month represented by the month portion of a java.time.ZonedDateTime. I've come up with three ways that appear to work. Given:

ZonedDateTime date = _some date_;

Option 1:

int daysInMonth = date.getMonth().length(date.getChronology().isLeapYear(date.getYear()));

Option 2:

int daysInMonth = date.getMonth().length(date.toLocalDate().isLeapYear());

Option 3:

int daysInMonth = YearMonth.from(date).lengthOfMonth();

I discovered option 3 while checking this question for duplicates (Number of days in particular month of particular year?). Am I missing any other options? Is one of these options superior to another? Under what circumstances will that superiority manifest?

If I'm reading things correctly, the first one appears to be the only one capable of supporting chronologies other than IsoChronology. That's not important for the use case at hand, but I do like to write flexible, reusable code, and I'd like for this to not fall down in other situations. I'm not an expert on those alternative chronologies, and I don't know if they have leap years or anything else that might cause the length of a month to vary. Heck, I don't even know if they have months.

EDIT: Option 4, per @Ole V.V.'s answer, below:

int daysInMonth = date.toLocalDate().lengthOfMonth();

Solution

  • LocalDate#lengthOfMonth

    I believe my preference is for using LocalDate#lengthOfMonth.

    int daysInMonth = date.toLocalDate().lengthOfMonth();
    

    I understand your confusion. There are several ways to do this, and the above is not the only good way. In particular, I’m pretty fond of your option 3 too. The options explicitly involving isLeapYear() are not to my taste, I find them too low-level, and too manual.

    Under what circumstances will that superiority manifest?

    Readability and absence of surprises are the kings. From there your judgement is at least as good as mine. Chances are that you know the people who are going to maintain your code better than I do.

    Code that I can read without remembering the fact that the answer in a minority of cases depends on leap years, is easier to read. The remaining two options each have their advantages:


    Can you obtain your end goal some other, smarter way?

    You may also take a step back and ask yourself what you need the number of days in a month for. I am mentioning this because one typical use would be for calculations that java.time can itself do better than you can, like adding 24 days to a date, finding the count of days between two dates in different months or finding out which day of the year a certain date is. java.time has got methods for all of these and many more.