Search code examples
javadatecalendar

Getting last day of the month in a given string date


My input string date is as below:

String date = "1/13/2012";

I am getting the month as below:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
String month = new SimpleDateFormat("MM").format(convertedDate);

But how do I get the last calendar day of the month in a given String date?

E.g.: for a String "1/13/2012" the output must be "1/31/2012".


Solution

  • Java 8 and above.

    By using convertedDate.getMonth().length(convertedDate.isLeapYear()) where convertedDate is an instance of LocalDate.

    String date = "1/13/2012";
    LocalDate convertedDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/d/yyyy"));
    convertedDate = convertedDate.withDayOfMonth(
                                    convertedDate.getMonth().length(convertedDate.isLeapYear()));
    

    Java 7 and below.

    By using getActualMaximum method of java.util.Calendar:

    String date = "1/13/2012";
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    Date convertedDate = dateFormat.parse(date);
    Calendar c = Calendar.getInstance();
    c.setTime(convertedDate);
    c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));