[Swift] 현재 날짜가 속해있는 주간 날짜 구하기

2024. 3. 5. 21:38Swift

↑https://dongjin97-ios.tistory.com/6

 

[Swift] Date locale + 현재 날짜가 속해있는 주간 날짜 구하기 (수정버전)

Date 이전 글에서 포스팅한 것중 잘못된 생각이 있어서 붙잡기위해서 다시 글작성 ! 로직을 설명하기 앞서 주의사항 ! 해당 값들을 Print문으로 출력하면 하루 밀려서 나오게 되는 현상이 발생 →

dongjin97-ios.tistory.com

↑수정 버전 ↑

 

 

현재 진행하고 있는 프로젝트에서 현재 날짜가 속해 있는 주간 날짜를 구하는 로직이 필요해서 해당 기능을 구현하게 되었습니다.

주간 날짜구하기

Foundation의 Calendar와 Date를 활용해서 주간 날짜를 구할수 있습니다.

 

주간 날짜 구하는 로직

! 로직을 설명하기 앞서 주의사항 !

해당 값들을 Print문으로 출력하면 하루 밀려서 나오게 되는 현상이 발생  → DateFormatter()로 format하면 정상적으로 출력된다

 

1. 현재 날짜가 속해 있는 주의 월요일 날짜 구하기

코드

(1) guard let result = calendar.dateInterval(of: .weekOfYear, for: Date()) else { return } 
(2) guard let weeklyStartDate = calendar.date(byAdding: .day, value: 1, to: result.start)

 

코드 설명 

  • dateInterval : 특정 시작날짜와 종료 날짜 사이의 시간범위를 구하는 Calendar 함수 
  • weekOfYear : 한주를 나타냄
  • date(byAdding: 기준(년,월,달,시간,분,초), valuse : 늘리거나 줄이는 기준, to: 특정날짜)

(1) 현재날짜를 기준으로 시작날짜와 종료날짜

 - result.start = 시작날짜

(2) 시작날짜에 하루날짜를 추가

이유 : 시작날짜가 일요일부터 시작 → 월요일부터 시작으로 하기 위해서 날짜추가

 

 

2. 현재 날짜가 속해 있는 달의 마지막 날짜 구하기

  • 주간 날짜가 달을 넘어 갈수도 있기때문에 현재날짜를 가지고 있는 달의 마지막 날짜도 필요합니다.

Ex (2.26) (2.27) (2.28) (2.29) (3.1) (3.2)

코드

(1) let components = calendar.dateComponents([.year, .month], from: Date())
(2) guard let currentStartDate = calendar.date(from: components) else { return }
(3) guard let nextStartDate = calendar.date(byAdding: .month, value: 1, to: currentStartDate) else { return }
(4) guard let currentEndDate = calendar.date(byAdding: .day, value: -1, to: nextStartDate)?.dateToString(format: "dd") else { return }

코드 설명 

 

  • components : 이번년도와 이번달 (현재 날짜가 속해 있는)
  • currentStartDate : 이번달의 첫번째날
  • nextStartDate : 다음 달의 첫번째날
  • currentEndDate : 이번달의 가장 마지막날

이번달의 가장 마지막날 구하는 로직

다음달의 첫번째날의 이전날 = 이번달의 첫째날

(1)(2)코드를 활용해서 이번달의 첫째날 구하기 -> (3) date함수 사용하여 다음달의 첫째날 구하기 -> (4) 다음날의 첫째날의 이전달 구하기 = 이번달의 가장 마지막날

3 월요일 날짜에서 +1씩 진행하여 주간 날짜 데이터 구하기

1. 앞에서 구한 마지막날짜를 활용 → 마지막 날짜를 안넘길 경우

  • 원래대로 +1씩 날짜를 늘려 날짜 데이터 추가

2. 앞에서 구한 마지막날짜를 활용 → 마지막 날짜를 넘길 경우

  • 날짜를 넘긴 날부터는 마지막 날짜만큼 빼주고 난뒤 날짜 데이터에 추가
 for i in 0...6 {
            let date = weeklyStartDateInt + i
            if date <= currentEndDateInt {
                weeklyDates.append(date)
            } else {
                weeklyDates.append(date - currentEndDateInt)
            }
}

변수 설명 

 

weeklyStartDateInt : 주에 시작 날짜를 Int형으로 변환한 변수 

currentEndDateInt : 한달에 마지막 날짜를 Int형을 변환한 변수

weeklyDates : 주간 데이터를 담는 Int형 배열

전체 코드

var weeklyDates : [Int] = []
        let calendar = Calendar.current
        
        // MARK: - 현재 주의 시작 날짜
        
        guard let result = calendar.dateInterval(of: .weekOfYear, for: Date()) else { return } // 현재 날짜가 속해있는 토요일부터 토요일까지 날짜 보여줌
        guard let weeklyStartDate = calendar.date(byAdding: .day, value: 1, to: result.start)?.dateToString(format: "dd") else { return }
        
        // MARK: - 현재 주의 마지막 날짜
        
        let components = calendar.dateComponents([.year, .month], from: Date()) // 현재 날짜의 년도와 월
        guard let currentStartDate = calendar.date(from: components) else { return } // 날짜와 년도를 가지고 가장 첫번째 날짜 Get
        guard let nextStartDate = calendar.date(byAdding: .month, value: 1, to: currentStartDate) else {return} // 다음 달의 가장 첫번쨰날
        guard let currentEndDate = calendar.date(byAdding: .day, value: -1, to: nextStartDate)?.dateToString(format: "dd") else {return} // 다음달의 가장 첫번째날 이전날 = 이번달의 마지막날
        
        // MARK: - 주간 데이터 구하기
        
        guard let weeklyStartDateInt = Int(weeklyStartDate) else { return }
        guard let currentEndDateInt = Int(currentEndDate) else { return }
        
        for i in 0...6 {
            let date = weeklyStartDateInt + i
            
            if date <= currentEndDateInt {
                weeklyDates.append(date)
            } else {
                weeklyDates.append(date - currentEndDateInt)
            }
        }
        
        weeklyCalendarView.setWeeklyDates(weeklyDates: weeklyDates)