If you have Java 8, you can use this code:
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; public class SoLastDayJava8 { static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); public LocalDate lastDay(final String yyyy_MM_dd) { LocalDate givenDate = LocalDate.parse(yyyy_MM_dd, formatter); return givenDate.with(TemporalAdjusters.lastDayOfMonth()); } }
The test code changes a bit.
public class SoLastDayJava8Test { @Test public void testLastDay() throws Exception { SoLastDayJava8 soLastDay = new SoLastDayJava8(); String date1 = "2015-01-27"; System.out.printf("Date %s becomes %s.\n", date1, soLastDay.lastDay(date1)); String date2 = "2015-02-02"; System.out.printf("Date %s becomes %s.\n", date2, soLastDay.lastDay(date2)); } }
But the results are the same.
The date 2015-01-27 becomes 2015-01-31.
The date 2015-02-02 becomes 2015-02-28.
source share