I need to get the first date (as org.joda.time.LocalDate
) of a month and the last one. Getting the first is trivial, but getting the last seems to need some logic as months have different length and February length even varies over years. Is there a mechanism for this already built in to JodaTime or should I implement it myself?
To get the last day of the month we first need to find out the last date of the month. To do this, create a new instance of a DateTime . From the DateTime object get the day-of-the-month property by calling the dayOfMonth() method. Then call the withMaximumValue() method which will give us the last date of a month.
Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);
How about:
LocalDate endOfMonth = date.dayOfMonth().withMaximumValue();
dayOfMonth()
returns a LocalDate.Property
which represents the "day of month" field in a way which knows the originating LocalDate
.
As it happens, the withMaximumValue()
method is even documented to recommend it for this particular task:
This operation is useful for obtaining a LocalDate on the last day of the month, as month lengths vary.
LocalDate lastDayOfMonth = dt.dayOfMonth().withMaximumValue();
Another simple method is this:
//Set the Date in First of the next Month: answer = new DateTime(year,month+1,1,0,0,0); //Now take away one day and now you have the last day in the month correctly answer = answer.minusDays(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With