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"
.
Use the getActualMaximum() method to get the last day of the month. int res = cal. getActualMaximum(Calendar. DATE);
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.
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()));
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With