문제

I have an issue: setFirstWeekDay doesn't work... I don't know why ...

 NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorianT setFirstWeekday:2];
 NSDateFormatter *formatDayWeek = [[NSDateFormatter alloc] init];
    [formatDayWeek setDateFormat:@"c EEEE"];

    NSLog(@"date : %@  value for date : %@", dateForMonth, [formatDayWeek stringFromDate:dateForMonth]);

This is what I got:

date : 2012-11-23 14:18:28 +0000  value for date : 6 Friday

And I should get date : 2012-11-23 14:18:28 +0000 value for date : 5 Friday

도움이 되었습니까?

해결책

The issue is that you are really dealing with three separate objects here: an NSCalendar, an NSDate, and an NSDateFormatter (which is not using the NSCalendar object you created). The three aren't implicitly connected; when you pass in the NSDate to the date formatter, you're completely pulling your custom NSCalendar, with the modified weekday, out of the equation. Remember: an NSDate object is simply a measure of time from a reference point (such as number of seconds from 1/1/2001 Midnight GMT)... it's the calendar object that has the concept of "day name," day ordinality," etc for that measure of time.

If you want to see the modified ordinality, pass in your calendar object to the formatter:

NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];

NSDateFormatter *formatDayWeek = [[NSDateFormatter alloc] init];
[formatDayWeek setCalendar:gregorianT];
[formatDayWeek setDateFormat:@"c EEEE"];

NSLog(@"Value for date: %@", [formatDayWeek stringFromDate:dateForMonth]);

...or you can access the ordinality directly from your NSCalendar object.

NSCalendar *gregorianT = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorianT setFirstWeekday:2];

NSUInteger valueOfDay = [gregorianT ordinalityOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:dateForMonth];

NSLog(@"Value for date : %ld", (long)valueOfDay);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top