Find the NSDate for next Monday

ChandreshKanetiya picture ChandreshKanetiya · Aug 9, 2013 · Viewed 7.4k times · Source

I want to get the date of the next Monday after the current date.

So if today's date is 2013-08-09 (Friday) then I want to get the date 2013-08-12.

How can I do this?

Answer

Lucas Eduardo picture Lucas Eduardo · Aug 9, 2013

This piece of code should get what you want. It simply calculates how many days are from monday and append it from current's date.

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSWeekdayCalendarUnit fromDate:now];

NSUInteger weekdayToday = [components weekday];  
NSInteger daysToMonday = (9 - weekdayToday) % 7;

NSDate *nextMonday = [now dateByAddingTimeInterval:60*60*24*daysToMonday];

Untested, but should work, and without worrying about changing first dates of calendar.

And it can even be easily addapted to every another day of the week, just change the 9inside (9 - weekdayToday) % 7; by 7 + weekDayYouWant, remembering that sunday = 1, monday = 2...