Reputation: 21281
I have a YearMonth
instance, is there an easy way to figure what the last day, in LocalDate
, of that instance is?
I know there is a toLocalDate(int day)
, but I may not know if the month has the 31st day or not.
Of course, I can always put the code in a try-catch block and try with 31
first then if that fails, try with 30
(or 29
, or 28
for Feb).
Is there a cleaner way?
Upvotes: 2
Views: 229
Reputation: 338316
Update: The Joda-Time project is now in maintenance-mode, recommending a migration to its official replacement: The java.time classes built into Java 8 and later, as defined in JSR 310.
java.time.YearMonth
.of ( 2020 , Month.FEBRUARY )
.atEndOfMonth()
2020-02-29
YearMonth#atEndOfMonth
Simply call the atEndOfMonth
method.
java.time.LocalDate endOfMonth = java.time.YearMonth
.of ( 2020 , Month.FEBRUARY )
.atEndOfMonth() ;
See this code run at Ideone.com.
2020-02-29
Upvotes: 1
Reputation: 44061
Eiter the answer of @MartinMilan (a standard algorithm working in most libraries) or following built-in solution of JodaTime-library:
YearMonth ym = YearMonth.now();
LocalDate endOfMonth = ym.toLocalDate(1).dayOfMonth().withMaximumValue();
Upvotes: 0