Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last date of a particular month with JodaTime?

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?

like image 928
Ivan Avatar asked Mar 14 '12 22:03

Ivan


People also ask

How to get last day of month in Joda Time?

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.

How to get end day of month in Java?

Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);


2 Answers

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(); 
like image 149
Jon Skeet Avatar answered Oct 14 '22 19:10

Jon Skeet


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); 
like image 21
Abraham Maldonado Barrios Avatar answered Oct 14 '22 18:10

Abraham Maldonado Barrios