javadatedatetimecalendar

Java get FirstDate and LastDate of following month in MM/dd/yyyy format even if the input is not the first day of the month


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

Solution

  • Don't use Date as it is obsolete and buggy. Use LocalDate and other classes from the java.time package.

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
    LocalDate date = LocalDate.parse("12/22/2020", dtf);
    date = date.plusMonths(1);
    LocalDate endDate = date.withDayOfMonth(date.lengthOfMonth());
    LocalDate startDate = date.withDayOfMonth(1);
    System.out.println("FirstDate: " +startDate.format(dtf));
    System.out.println("LastDate:  " +endDate.format(dtf));
    

    prints

    FirstDate: 01/01/2021
    LastDate:  01/31/2021