NSCalendar, why does setting the firstWeekday doesn't effect calculation outcome?

前端 未结 3 1768
不思量自难忘°
不思量自难忘° 2020-12-19 09:31

i need to calculate the weekday for a given date, however, depending on the calendar a week can star on Monday and somwhere on Sunday

so i wanted to set it, to start

3条回答
  •  抹茶落季
    2020-12-19 10:03

    I believe you need to use the ordinalityOfUnit:inUnit:forDate: method rather than attempting to extract the date components. So something like this:

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

    Basically that call is asking for the day (NSWeekdayCalendarUnit) in the week (NSWeekCalendarUnit) for the given date.

    If that doesn't work as is, you may need to create your own calendar, rather than trying to modifying the first week day on the currentCalendar.

    For example:

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

    Then use that new calendar object rather than [NSCalendar currentCalendar] in the ordinalityOfUnit:inUnit:forDate: call.

提交回复
热议问题