Get the date of next saturday in Objective-C?

早过忘川 提交于 2019-11-28 11:47:29

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

Calendrical Calculations

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);

[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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!