Vicky Vicky - 5 months ago 9
Java Question

getting last day of the month in 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 given String date ?

For e.g. for String "1/13/2012" output should come as date "1/31/2012"

Answer

By using getActualMaximum method of java.util.Calendar:

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));