How to print a calendar for a specific month and year in Scala

1 Answer

0 votes
import java.time.{LocalDate, YearMonth, DayOfWeek}
import java.time.format.TextStyle
import java.util.Locale

object CalendarPrinter:

  def printMonth(year: Int, month: Int): Unit =
    val ym = YearMonth.of(year, month)
    val first = ym.atDay(1)
    val daysInMonth = ym.lengthOfMonth()
    val monthName = ym.getMonth.getDisplayName(TextStyle.FULL, Locale.getDefault)

    println(s"     $monthName $year")
    println("Su Mo Tu We Th Fr Sa")

    // DayOfWeek: Monday=1 ... Sunday=7
    val offset = first.getDayOfWeek.getValue % 7  // convert Sunday→0

    print("   " * offset)

    for day <- 1 to daysInMonth do
      print(f"$day%2d ")
      if ((offset + day) % 7 == 0) then println()

    println()

  @main def run(): Unit =
    printMonth(2026, 1)





/*
run:

     January 2026
Su Mo Tu We Th Fr Sa
             1  2  3 
 4  5  6  7  8  9 10 
11 12 13 14 15 16 17 
18 19 20 21 22 23 24 
25 26 27 28 29 30 31 

*/


 



answered Jan 19 by avibootz

Related questions

...