Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get a date that next weekday from a date. (iOS, Xcode 4.4.1, ARC)
- (NSDate*)dateOfNextWeekday:(NSInteger)weekday fromDate:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
// 渡された日付から曜日を取り出します。
NSDateComponents* baseComponents = [calendar components:NSWeekdayCalendarUnit fromDate:date];
NSDateComponents* addingComponents = [[NSDateComponents alloc] init];
// 指定された曜日だけ進めます。
NSInteger addingDay = weekday - baseComponents.weekday;
// 同じ曜日か手前の曜日の場合は 0 以下になるので、そのときは一週間先を指定します。
if (addingDay <= 0) addingDay += 7;
// 目的の曜日の日付を取得します。
addingComponents.day = addingDay;
return [calendar dateByAddingComponents:addingComponents toDate:date options:0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment