Search code examples
objective-cnsdatensdatecomponentsnsdatecomponent

Change NSDate to Friday of that Week


Currently I have the below code to increment my days to the next friday, however what I need is to get the friday of the current week. For example if it is last Sunday, 03/01. I would expect my response to be last Friday(02/28) not Friday(03/06).

I have checked other answers but am getting confused with how to implement a clean way to accomplish this.

+ (NSDate *)getLastFridayYearsMonthStartingDate:(NSDate *)date {

NSDateComponents *dateComponents = [[NSCalendar gregorianCalendar] components:NSYearCalendarUnit|NSCalendarUnitDay|NSCalendarUnitMonth|NSWeekdayCalendarUnit
                                                                     fromDate:date];

     // Set date to last year, +1 to account for previous business day
     [dateComponents setYear: -1];
     [dateComponents setDay:[dateComponents day]+1];


    // We always want the start date to be the friday of the given week, so we will increment the difference if not
    if ([dateComponents weekday] != 6) {
        NSInteger daysToFriday = (13 - [dateComponents weekday]) % 7;
        [dateComponents setDay:[dateComponents day]+daysToFriday];
    }

    NSDate *fridayDate = [[NSCalendar gregorianCalendar] dateFromComponents:dateComponents];

    return fridayDate;
}

Solution

  • try using setWeekday to set a specific day

    -(NSDate *) getFriday:(NSDate *)date {
        NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        [cal setTimeZone:[NSTimeZone systemTimeZone]];
    
        NSDateComponents *comp = [cal components:NSYearCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:date];
    
    
        [comp setWeekday:6];
        [comp setHour:0];
        [comp setMinute:0];
        [comp setSecond:0];
        return [cal dateFromComponents:comp];
    }