How to find the dates of the last Fridays of each month of a given year in Scala

1 Answer

0 votes
import java.time.{DayOfWeek, LocalDate}
import java.time.format.DateTimeFormatter

object LastFridaysOfYearProgram {

  // Return all last Fridays of each month in a given year
  def lastFridaysOfYear(year: Int): Seq[LocalDate] = {
    for (month <- 1 to 12) yield {

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

      // Walk backward to Friday
      while (date.getDayOfWeek != DayOfWeek.FRIDAY) {
        date = date.minusDays(1)
      }

      date
    }
  }

  def main(args: Array[String]): Unit = {

    val year: Int =
      if (args.nonEmpty) args(0).toInt
      else 2026

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

    for (date <- lastFridaysOfYear(year)) {
      println(date.format(fmt))
    }
  }
}



/*
run:

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

*/

 



answered 4 hours ago by avibootz

Related questions

...