Thursday, June 13, 2013

NSCalendar setMinimumDaysInFirstWeek example in Objective C (iOS).


NSCalendar setMinimumDaysInFirstWeek

Sets the minimum number of days in the first week of the receiver.

- (void)setMinimumDaysInFirstWeek:(NSUInteger)mdw

Parameters of [NSCalendar setMinimumDaysInFirstWeek]
mdw
The minimum number of days in the first week of the receiver.

NSCalendar setMinimumDaysInFirstWeek example.
Since iOS5 NSCalender dosent seem to be defining accordingly to ISO 8601 as default. You need to set your calender with method "setMinimumDaysInFirstWeek" to get expected week number result.

[yourCalender setMinimumDaysInFirstWeek:4];
"4" means Thursday in this case.

Example of [NSCalendar setMinimumDaysInFirstWeek].
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
int minWeeks, maxWeek;
minWeeks=maxWeek=0;
for (int weekCounter=1; weekCounter<=7; weekCounter++) {
    [gregorian setMinimumDaysInFirstWeek:weekCounter];
    [gregorian setFirstWeekday:2];
    NSDate* sourceDate = [NSDate date];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* today = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
    NSDateComponents *todaysComponents = [gregorian components:NSWeekCalendarUnit fromDate:today];
    NSUInteger todaysWeek = [todaysComponents week];

    if (todaysWeek>maxWeek) {
        maxWeek=todaysWeek;
    }
    if (todaysWeek<minWeeks || minWeeks==0) {
        minWeeks=todaysWeek;
    }
}
NSLog(@"min:%d, max:%d", minWeeks, maxWeek);

NSCalendar setMinimumDaysInFirstWeek example.
cal setFirstWeekday:2];            //week starts on Monday
[cal setMinimumDaysInFirstWeek:4];  //first week in the year containing 4 day

End of NSCalendar setMinimumDaysInFirstWeek example article.