[swift] SwiftDate를 사용하여 지정된 기간 동안의 특정 요일의 마지막 날짜 가져오기

Swift는 간편하게 날짜 및 시간을 다룰 수 있는 SwiftDate 라이브러리를 제공합니다. 이 라이브러리를 사용하여 특정 기간 동안의 특정 요일의 마지막 날짜를 가져와 보겠습니다.

SwiftDate 설치

먼저, SwiftDate를 프로젝트에 추가해야 합니다. Cocoapods를 사용하고 있다면 Podfile에 다음 줄을 추가하고, pod install을 실행하여 SwiftDate를 설치할 수 있습니다.

pod 'SwiftDate'

코드 예제

아래는 SwiftDate를 사용하여 지정된 기간 동안의 특정 요일의 마지막 날짜를 가져오는 예제입니다.

import SwiftDate

func getLastDayOfWeekday(for weekday: Weekday, during period: ClosedRange<Date>) -> Date? {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy/MM/dd"
    
    let startDateString = formatter.string(from: period.lowerBound)
    let endDateString = formatter.string(from: period.upperBound)
    
    let startDate = DateInRegion(startDateString, format: .custom("yyyy/MM/dd"))
    let endDate = DateInRegion(endDateString, format: .custom("yyyy/MM/dd"))
    
    let occurrences = (startDate...endDate).byWeekdays([weekday])
    let lastDate = occurrences.last?.end
    
    return lastDate?.date
}

// 예제 사용
let mondayLastDate = getLastDayOfWeekday(for: .monday, during: Date()...(Date() + 1.year) )
print(mondayLastDate)

위의 예제 코드에서는 getLastDayOfWeekday 함수를 정의합니다. 이 함수는 weekdayperiod 두 매개변수를 받아서 해당 기간 동안의 특정 요일의 마지막 날짜를 리턴합니다.

이 함수를 사용하는 예제에서는 getLastDayOfWeekday 함수를 호출하여 현재 날짜부터 1년 이후까지의 기간 동안의 월요일의 마지막 날짜를 구하는 예제입니다. mondayLastDate 변수에는 결과값이 저장되어 출력됩니다.

결과는 다음과 같이 특정 요일의 마지막 날짜를 출력할 것입니다.

Optional(2022-12-26 00:00:00 +0000)

이제 SwiftDate를 사용하여 지정된 기간 동안의 특정 요일의 마지막 날짜를 쉽게 구할 수 있습니다.