How to find the dates of the last Sunday of each month of a given year in Java

1 Answer

0 votes
import java.time.format.DateTimeFormatter;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class LastSundays {

    // Return all last Sundays of each month in a given year
    public static List<LocalDate> lastSundaysOfYear(int year) {
        List<LocalDate> results = new ArrayList<>(12);

        for (int month = 1; month <= 12; month++) {

            // Last day of the month
            LocalDate date = LocalDate.of(year, month, 1)
                    .plusMonths(1)
                    .minusDays(1);

            // Walk backward to Sunday
            while (date.getDayOfWeek() != DayOfWeek.SUNDAY) {
                date = date.minusDays(1);
            }

            results.add(date);
        }

        return results;
    }

    public static void main(String[] args) {

        int year = (args.length > 0)
                ? Integer.parseInt(args[0])
                : 2026;

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/yyyy");

        for (LocalDate date : lastSundaysOfYear(year)) {
            System.out.println(date.format(fmt));
        }
    }
}


/*
run:

01/25/2026
02/22/2026
03/29/2026
04/26/2026
05/31/2026
06/28/2026
07/26/2026
08/30/2026
09/27/2026
10/25/2026
11/29/2026
12/27/2026

*/

 



answered 13 hours ago by avibootz

Related questions

...