Skip to content

Instantly share code, notes, and snippets.

@es-kumagai
Created August 8, 2012 10:46
Show Gist options
  • Save es-kumagai/3294175 to your computer and use it in GitHub Desktop.
Save es-kumagai/3294175 to your computer and use it in GitHub Desktop.
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