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

1 Answer

0 votes
import java.time.LocalDate
import java.time.DayOfWeek
import java.time.format.DateTimeFormatter

// Return all last Sundays of each month in a given year
fun lastSundaysOfYear(year: Int) = sequence {

    for (month in 1..12) {

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

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

        yield(date)
    }
}

fun main(args: Array<String>) {

    val year: Int =
        if (args.isNotEmpty())
            args[0].toInt()
        else
            2026

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

    for (date in lastSundaysOfYear(year)) {
        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 May 24 by avibootz

Related questions

...