iPhone NSDate eg. next Friday

前端 未结 5 929
予麋鹿
予麋鹿 2021-01-14 03:22

I want to create a function which results the date of next Friday but I have no plan how to do it. Has anyone a good hint to me ?

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-14 04:07

    This should work

    + (NSDate *) dateForNextWeekday: (NSInteger)weekday {
    
    NSDate *today = [[NSDate alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    
    // Get the weekday component of the current date
    NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
                                                       fromDate:today];
    
    /*
     Add components to get to the weekday we want
     */
    NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
    NSInteger dif = weekday-weekdayComponents.weekday;
    if (dif<=0) dif += 7;
    [componentsToSubtract setDay:dif];
    
    NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
                                                         toDate:today options:0];
    
    return beginningOfWeek;
    

    }

提交回复
热议问题