Get the date of next saturday in Objective-C?

前端 未结 3 648
一向
一向 2020-12-10 22:14

How would you get the date of the the first saturday that occurs after today in Objective-C for iOS?

相关标签:
3条回答
  • 2020-12-10 22:28

    This will guide you through the process of manipulating calendar dates:

    Calendrical Calculations

    0 讨论(0)
  • 2020-12-10 22:45
    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *date = [NSDate date];
    NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
    NSInteger todayWeekday = [weekdayComponents weekday];
    
    enum Weeks {
        SUNDAY = 1,
        MONDAY,
        TUESDAY,
        WEDNESDAY,
        THURSDAY,
        FRIDAY,
        SATURDAY
    };
    
    NSInteger moveDays=SATURDAY-todayWeekday;
    if (moveDays<=0) {
        moveDays+=7;
    }
    
    NSDateComponents *components = [NSDateComponents new];
    components.day=moveDays;
    
    NSCalendar *calendar=[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDate* newDate = [calendar dateByAddingComponents:components toDate:date options:0];
    
    NSLog(@"%@",newDate);
    
    0 讨论(0)
  • 2020-12-10 22:48

    [NSDate dateWithNaturalLanguageString: @"next Saturday"]


    Edit: Starting in OS X 10.9 and iOS 8, you can do this:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSDate *now = [NSDate date];
    NSDateComponents *saturday = [[NSDateComponents alloc] init];
    saturday.weekday = 7 /* Saturday */;
    
    NSDate *nextSaturday = [calendar nextDateAfterDate:now matchingComponents:saturday options:0];
    
    0 讨论(0)
提交回复
热议问题