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

1 Answer

0 votes
import Foundation

func printMonth(year: Int, month: Int) {
    var calendar = Calendar.current
    calendar.firstWeekday = 1   // 1 = Sunday

    // First day of the month
    let firstComponents = DateComponents(year: year, month: month, day: 1)
    guard let firstDay = calendar.date(from: firstComponents) else { return }

    // Number of days in the month
    let range = calendar.range(of: .day, in: .month, for: firstDay)!
    let daysInMonth = range.count

    // Month name
    let formatter = DateFormatter()
    formatter.dateFormat = "LLLL"
    let monthName = formatter.string(from: firstDay)

    print("     \(monthName) \(year)")
    print("Su Mo Tu We Th Fr Sa")

    // Offset: Sunday = 1 → 0 spaces
    let weekday = calendar.component(.weekday, from: firstDay)
    let offset = weekday - 1

    for _ in 0..<offset {
        print("   ", terminator: "")
    }

    for day in 1...daysInMonth {
        print(String(format: "%2d ", day), terminator: "")
        if (offset + day) % 7 == 0 {
            print()
        }
    }

    print()
}

printMonth(year: 2026, month: 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

...