Search code examples
datejava-8localdatetimedate-manipulation

How to get a specific date of next month? (Java 8)


With today's date, I should get the 16th date of next month.

For example, on passing 13-12-2021, I should get 16-01-2022.

I need to get the next month 16th day from current date (input date). Examples:

  • On passing 13-11-2021 should get 16-12-2021.
  • On passing 14-11-2021 should get 16-12-2021.
  • On passing 15-11-2021 should get 16-12-2021.
  • On passing 02-12-2021 should get 16-01-2022.
  • On passing 03-12-2021 should get 16-01-2022.
  • On passing 03-01-2022 should get 16-02-2022.
  • On passing 04-01-2022 should get 16-02-2022.

Any help will be much appreciated. Thanks.


Solution

  • java.time

    One of the many strong points of java.time, the modern Java date and time API, is date arithmetic like this.

    public static LocalDate nthDayOfFollowingMonth(
            int desiredDayOfMonth, LocalDate currentDate) {
        return YearMonth.from(currentDate)
                .plusMonths(1)
                .atDay(desiredDayOfMonth);
    }
    

    Try it out with your example date:

        System.out.println(nthDayOfFollowingMonth(
                16, LocalDate.of(2021, Month.DECEMBER, 13)));
    

    Output:

    2022-01-16

    We might not have needed to convert to YearMonth and back to LocalDate. Doing so relieves both me and the reader of considering what happens if today’s day of month doesn’t exist in next month — for example if current date is 30 January (there is no 30 February). What one still wants to consider is what happens if you request a day of month tht doesn’t exist next month. For example on 13 January asking for the 30th of next month. We can try that out too:

        System.out.println(nthDayOfFollowingMonth(
                30, LocalDate.of(2022, Month.JANUARY, 13)));
    

    I find the result very reasonable:

    java.time.DateTimeException: Invalid date 'FEBRUARY 30'