I'd like to check whether a NSDate is in the same week as today. Therefore I'm consider the weekOfYear
s from a NSDateComponents
like mentioned in this post.
- (BOOL)dateIsThisWeek:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setFirstWeekday: 2]; // Added in second try
NSDate *today = [NSDate date];
NSDateComponents *todaysComponents = [cal components:NSCalendarUnitWeekOfYear fromDate: today];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [cal components:NSCalendarUnitWeekOfYear fromDate: date];
NSUInteger anotherWeek = [otherComponents weekOfYear];
return todaysWeek == anotherWeek; // todaysWeek=7 | anotherWeek=8
}
In my example I've the following dates:
today: 2017-02-15 12:00:00 +0000
date: 2017-02-18 12:00:00 +0000
The problem is, that todaysWeek
is set to 7 and anotherWeek
to 8 and I can not imagine why.
I thought that the problem might be, that the week is starting on a Sunday, so I set the first weekday of the calendar to 2 (Monday), but unfortunately without any success.
UPDATE
I've also tried this code but unfortunately with the same result:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate: date];
NSUInteger datesWeek = [otherComponents weekOfYear];
return todaysWeek==datesWeek; // todaysWeek=7 | datesWeek=8
Both dates should be in week number 7 like multiple websites are describing.