2016-12-30 3 views
1

오늘은 Friday입니다. 이는 NSCalendar에 따라 6입니다. 나는날짜 구성 요소를 빼는 방법은 무엇입니까?

Calendar.current.component(.weekday, from: Date()) 

가 어떻게 7을해야하는 Saturday 지난 주 평일 구성 요소를 얻는 다음을 사용하여이받을 수 있나요?

만약 내가 Calendar.current.component(.weekday, from: Date()) - 6입니다. 유효한 구성 요소가 아닌 0이 표시됩니다.

+0

지난 토요일의 날짜를 원하십니까? –

+0

아니요, 저는 7이라는 구성 요소를 원합니다. 기본적으로 구성 요소를 빼는 방법을 알고 싶습니다. 예를 들어 월요일은 2입니다. 3 일 전에 하루의 구성 요소를 알고 싶다면 금요일은 6이되어야합니다.하지만 2 - 3을하면 -1이 발생합니다. 이는 유효하지 않습니다. 희망은 내가 분명합니다 – Coder221

+0

당신은 날짜를 빼고 하루를 빼고 구성 요소를 뺀 것이 아닙니다 – Tj3n

답변

2

당신이 먼저 날짜를 얻을 그것에서 다시 뺄 필요가,이 시도 : 그 내용은

var dayComp = DateComponents() 
dayComp.day = -6 
let date = Calendar.current.date(byAdding: dayComp, to: Date()) 
Calendar.current.component(.weekday, from: date!) 
+0

이 솔루션은 완벽하게 작동합니다. – Coder221

2

가 먼저 calendar.date(byAdding:value:to:)을 사용하여 해당 날짜를 얻을 다음에서 일 번호를 얻을 필요가있다.

extension Date { 
    func getDateFor(days:Int) -> Date? { 
     return Calendar.current.date(byAdding: .day, value: days, to: Date()) 
    } 
} 

이제 간단히 기능을 사용하여 날짜를 가져옵니다.

if let date = Date().getDateFor(days: -6) { 
    print(Calendar.current.component(.weekday, from: date)) 
} 
+1

감사합니다 :) – Coder221