Find last Saturday of a month in Swift

In this tutorial, we will see how to find the last Saturday of a month in Swift, that means I will print the date of the last Saturday.

First of all, to get any day of the month we need to import Foundation framework at the top of our program. This framework provides us with the necessary data types and functionalities for working with dates and calendars.

Syntex

import Foundation

Simply put the above code at the top of your program to import the Foundationframework into your project.

Create a function

Now, I will create a function below to find the last Saturday of a month.

The function will take two parameters, year and month, and return an optional Date that will represent the last Saturday of the specified month.

Example

func lastSaturdayOfMonth(year: Int, month: Int) -> Date? {
    // Create a Calendar instance to work with dates
    let calendar = Calendar.current

    // Create DateComponents for the last day of the next month
    let components = DateComponents(year: year, month: month + 1, day: 0)

    // Get the last day of the specified month
    guard let lastDayOfMonth = calendar.date(from: components) else { return nil }

    // Iterate backward through the last 7 days of the month
    for day in (0...6).reversed() {
        // Get dates by subtracting 'day' from the last day of the month
        if let date = calendar.date(byAdding: .day, value: -day, to: lastDayOfMonth),
           // Check if the current date is a Saturday (weekday == 7)
           calendar.component(.weekday, from: date) == 7 {
            return date // Return the last Saturday found
        }
    }
    return nil // Return nil if no Saturday is found in the month
}

In the above program, the lastSaturdayOfMonth function will take a year and a month as input and return the date of the last Saturday in that month.

I have used the Calendar class to calculate the last day of the month and also created a for loop to iterate through the last 7 days of the month (0 to 6, inclusive) in reverse order to find the last Saturday.

If the function successfully finds the last Saturday of the specified month, it returns a Date object representing that day.

If there’s no Saturday in the specified month or if the input is invalid, the function returns nil.

Usage Example

Now, In the usage example, we will see how to utilize the lastSaturdayOfMonth function to find and format the last Saturday of a specified month and year.

Example

// Attempt to find the last Saturday of January 2024
if let lastSat = lastSaturdayOfMonth(year: 2024, month: 1) {

    // If a valid date is returned, proceed with formatting and printing
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd" // Set the date format

    // Print the formatted last Saturday of the month
    print("Last Saturday of the month: \(dateFormatter.string(from: lastSat))")

} else {
    // If no Saturday is found in January 2024, print a message
    print("No Saturday found in the specified month.")
}

The above code will print the date of the last Saturday of January 2024.

Have a look at the complete code below.

import Foundation

func lastSaturdayOfMonth(year: Int, month: Int) -> Date? {
    let calendar = Calendar.current
    let components = DateComponents(year: year, month: month + 1, day: 0)

    guard let lastDayOfMonth = calendar.date(from: components) else { return nil }

    for day in (0...6).reversed() {
        if let date = calendar.date(byAdding: .day, value: -day, to: lastDayOfMonth),
           calendar.component(.weekday, from: date) == 7 {
            return date
        }
    }
    return nil
}

if let lastSat = lastSaturdayOfMonth(year: 2024, month: 1) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    print("Last Saturday of the month: \(dateFormatter.string(from: lastSat))")
} else {
    print("No Saturday found in the specified month.")
}

Output:

Last Saturday of the month: 2024-01-27

Leave a Reply

Your email address will not be published. Required fields are marked *