2013-06-01 2 views
5

은 내가 사용하여 주 월요일에 스타와 somwhere 그래서 내가 월요일에 시작하는, 그것을 설정하고 싶었 NSCalendar, firstWeekday 설정이 계산 결과에 영향을주지 않는 이유는 무엇입니까?

일요일

에 할 수있는 일정에 따라, 그러나, 주어진 날짜의 요일을 계산해야

[[NSCalendar currentCalendar] setFirstWeekday:2]; 

그러나 계산 결과는 동일

{ 
    [[NSCalendar currentCalendar] setFirstWeekday:1]; 
    NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date]; 
    NSInteger weekday = [weekdayComponents weekday] - 1; 
    NSLog(@"%d", weekday); 
} 
{ 
    [[NSCalendar currentCalendar] setFirstWeekday:2]; 
    NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date]; 
    NSInteger weekday = [weekdayComponents weekday] - 1; 
    NSLog(@"%d", weekday); 
} 

반환 동일한 번호,하지만 왜입니까?

답변

8

표시되는 동작이 정확합니다. weekday 구성 요소는 firstWeekday 속성의 영향을받지 않습니다. 일요일을 대표하는 날짜가있는 경우 일요일 저녁이나 월요일에 일요일에 시작합니다. 이것이 영향을 미치는 것은 날짜 구성 요소의 week 속성에있는 주 번호입니다.

+0

firstWeekday가 무엇을 가리키고 있든 상관없이 일요일은 항상 평일 0이됩니다. –

+5

일요일은 항상 1 – Sven

+3

일요일 1, 월요일 2, 화요일 3, 수요일 4, 금요일 5, 토요일 6 –

3

날짜 구성 요소를 추출하는 대신 ordinalityOfUnit:inUnit:forDate: 메서드를 사용해야한다고 생각합니다. 이 같은 뭔가 :

NSUInteger weekday = [[NSCalendar currentCalendar] ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:date]; 

는 기본적으로 그 호출은 지정된 날짜의 주 (NSWeekCalendarUnit)에서 일 (NSWeekdayCalendarUnit)을 요구한다.

그대로 작동하지 않는 경우 currentCalendar의 첫 번째 요일을 수정하지 않고도 자신의 캘린더를 만들어야 할 수도 있습니다. 예를 들어

:

NSCalendarIdentifier calendarIdentifier = [[NSCalendar currentCalendar] calendarIdentifier]; 
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:calendarIdentifier] autorelease]; 
[calendar setFirstWeekday:2]; 

그런 다음 ordinalityOfUnit:inUnit:forDate: 호출하는 새로운 calendar 객체가 아닌 [NSCalendar currentCalendar]를 사용합니다.

+0

NSWeekCalendarUnit은 더 이상 사용되지 않습니다 :/ –

+0

다른 주 단위 중 하나 인 'NSWeekOfMonthCalendarUnit' 또는'NSWeekOfYearCalendarUnit'을 사용해보세요. 이러한 맥락에서 그들은 실제로 의미가 없지만 시도해 볼만한 가치가 있습니다. –

+1

iOS 10에서 setFirstWeekday : 2는 아무 것도 변경하지 않습니다 ... – Dmitry

관련 문제