0x56794E
0x56794E

Reputation: 21281

Figure out the last day (in LocalDate) of a YearMonth instance - joda library

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

Answers (3)

Basil Bourque
Basil Bourque

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.

tl;dr

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

Meno Hochschild
Meno Hochschild

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

Martin Milan
Martin Milan

Reputation: 6390

Go to the 1st of the next month, and then subtract one day?

Upvotes: 1

Related Questions