[swift] SwiftDate를 사용하여 특정 주의 시작 날짜와 종료 날짜 사이의 특정 요일의 날짜 목록 가져오기

SwiftDate는 Swift 언어를 위한 강력한 날짜 및 시간 처리 라이브러리입니다. 이 라이브러리를 사용하여 특정 주의 시작 날짜와 종료 날짜 사이에서 특정 요일의 날짜 목록을 가져오는 방법을 알아보겠습니다.

1. SwiftDate 라이브러리 가져오기

먼저 SwiftDate 라이브러리를 프로젝트에 추가해야 합니다. 프로젝트의 Podfile에 다음과 같은 코드를 추가해주세요:

target 'YourApp' do
  use_frameworks!
  pod 'SwiftDate'
end

그런 다음 터미널에서 pod install 명령어를 실행하여 라이브러리를 설치해주세요.

2. 날짜 목록 가져오기

다음은 SwiftDate를 사용하여 특정 주의 시작 날짜와 종료 날짜 사이에서 특정 요일의 날짜 목록을 가져오는 예시 코드입니다:

import SwiftDate

func getDatesBetween(start: Date, end: Date, dayOfWeek: Int) -> [Date] {
    var resultDates: [Date] = []
    let calendar = Calendar.current
    
    let startOfWeek = start.startOfWeek
    let endOfWeek = end.endOfWeek
    
    let nextWeek = calendar.date(byAdding: .weekOfYear, value: 1, to: startOfWeek)!
    let daysToAdd = dayOfWeek - calendar.component(.weekday, from: startOfWeek)
    let nextDate = calendar.date(byAdding: .day, value: daysToAdd, to: startOfWeek)!
    
    if nextDate < startOfWeek {
        resultDates.append(nextDate)
    }
    
    while nextDate < endOfWeek {
        resultDates.append(nextDate)
        nextDate = calendar.date(byAdding: .weekOfYear, value: 1, to: nextDate)!
    }
    
    return resultDates
}

// 사용 예시
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"

let startDate = formatter.date(from: "2022/01/01")!
let endDate = formatter.date(from: "2022/12/31")!
let dayOfWeek = Calendar.current.weekdaySymbols.firstIndex(of: "Monday")! + 1

let dates = getDatesBetween(start: startDate, end: endDate, dayOfWeek: dayOfWeek)
for date in dates {
    print(formatter.string(from: date))
}

위의 예시 코드는 2022년도의 시작 날짜(startDate)와 종료 날짜(endDate) 사이에서 월요일(Monday)에 해당하는 날짜 목록을 가져옵니다. 결과는 날짜 형식에 맞게 출력됩니다.

결론

SwiftDate를 사용하여 특정 주의 시작 날짜와 종료 날짜 사이에서 특정 요일의 날짜 목록을 가져오는 방법을 알아보았습니다. SwiftDate를 활용하면 Swift 언어로 간편하게 날짜 및 시간 처리를 할 수 있습니다.

참고 자료