iPhone NSDate eg. next Friday

前端 未结 5 972
予麋鹿
予麋鹿 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 03:49

    Here is my solution, and just to warn you, on a saturday is the friday before shown. cheers to all

    NSDate *today = [[NSDate alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];
    int weekday = [weekdayComponents weekday];
    
    
    int iOffsetToFryday = -weekday + 6;
    weekdayComponents.weekday = iOffsetToFryday;
    
    NSDate *nextFriday = [[NSCalendar currentCalendar] dateByAddingComponents:weekdayComponents toDate:today options:0];
    

提交回复
热议问题