Cocoa get the first day of the week

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];
    // because sunday is 0, we need it to be 6
    NSInteger weekday = (([weekdayComponents weekday] + 6) % 7);

    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:self];
    [components setDay: -weekday + 2];

    return [calendar dateFromComponents:components];

}
+1
source share
1 answer

Itโ€™s easier to use a calendar method rangeOfUnitthat correctly processes the โ€œstart of the weekโ€ according to the current locale:

NSDate *date = your date;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfWeek;
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit
            startDate:&startOfWeek
             interval:NULL
              forDate:date];

NSDateComponents, ( , 7 ):

NSDate *date = your date;
NSDateComponents *comp = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSWeekdayCalendarUnit
                                     fromDate:date];
NSDate *startOfDay = [calendar dateFromComponents:comp];
NSInteger diff = (NSInteger)[calendar firstWeekday] - (NSInteger)[comp weekday];
if (diff > 0)
    diff -= 7;
NSDateComponents *subtract = [[NSDateComponents alloc] init];
[subtract setDay:diff];
NSDate *startOfWeek = [calendar dateByAddingComponents:subtract toDate:startOfDay options:0];
+7

Source: https://habr.com/ru/post/1540631/


All Articles