How to compute the day of the week for January 1st of any given year in Scala

1 Answer

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

/*
    This program determines the day of the week for January 1st of a given year.

    Approach:
    ---------
    Scala uses the Java Time API for date/time handling:
        - LocalDate.of(year, month, day) : constructs a calendar date
        - getDayOfWeek()                 : returns a DayOfWeek enum

    DayOfWeek values:
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
        FRIDAY, SATURDAY, SUNDAY

    This avoids manual calendar arithmetic and uses efficient built‑in routines.
*/

// Convert DayOfWeek enum to a readable string
def weekdayName(dow: DayOfWeek): String =
    dow.toString.toLowerCase.capitalize

// Compute weekday of January 1st for a given year
def jan1Weekday(year: Int): String = {
    val dateValue: LocalDate = LocalDate.of(year, 1, 1)  // January 1st of given year
    val dow: DayOfWeek = dateValue.getDayOfWeek          // Built‑in weekday computation
    
    weekdayName(dow)
}

@main def run(): Unit = {
    val year: Int = 2026

    val result: String = jan1Weekday(year)
    println(s"January 1st, $year falls on a $result.")
}



/*
run:

January 1st, 2026 falls on a Thursday.

*/

 



answered 9 hours ago by avibootz

Related questions

...