How to get the first day of the week for a date
it seems easier on this, since:
- when the week starts on Sunday, I need to return the date of Sunday.
- if it starts on monday i need to get the monday date
the input date is any date of the week with time ... I tried several approaches, but the extreme did it difficould
i created a function which, however, does not work 100% (not sure about [components setDay: -weekday + 2];)
- (NSDate *)firstDateOfWeek {
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents *weekdayComponents = [calendar components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
NSInteger weekday = (([weekdayComponents weekday] + 6) % 7);
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
[components setDay: -weekday + 2];
return [calendar dateFromComponents:components];
}
source
share