Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 879
Vicky Avatar asked Nov 29 '12 11:11

Vicky


People also ask

How can I get the last day of the current month in Android?

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

How do I get the last day of the month in Localdatetime?

The atEndOfMonth() method of YearMonth class in Java is used to return a LocalDate of the last day of month based on this YearMonth object with which it is used.


1 Answers

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)); 
like image 117
Aleksandr M Avatar answered Oct 23 '22 09:10

Aleksandr M