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();