I have a function below which has an input Date and it will return the first and last Date of the next month in MM/dd/yyyy
format.
String string = "01/01/2022";
DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date dt = sdf .parse(string);
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.MONTH, 1);
String firstDate = sdf.format(c.getTime());
System.out.println("FirstDate:" + firstDate);
c.add(Calendar.MONTH, 1);
c.add(Calendar.DAY_OF_MONTH, -1);
String lastDate = sdf.format(c.getTime());
System.out.println("LastDate:" + lastDate);
The above will give me an output like below
FirstDate:02/01/2022
LastDate:02/28/2022
This works well if the input is the first day of the previous month, what i would like to achieve is to get the FirstDate and LastDate of the next month
even if the input is a date which is not the first date of the month for example 01/31/2022
gives me the output below
FirstDate:02/28/2022
LastDate:03/27/2022
But i would still like it to give me the first out of
FirstDate:02/01/2022
LastDate:02/28/2022
DateFormat
,SimpleDateFormat
,Date
andCalendar
. Those classes are notoriously troublesome and long outdated. Instead useLocalDate
andDateTimeFormatter
, both from java.time, the modern Java date and time API.