Create next NSDate that matches day NSString
I would like to create an NSDate object that represents the next day that matches a NSString day.
For example. The NSString is MON or Monday I want to get the next N开发者_StackOverflow社区SDate that matches this day - it can be today aswell.
e.g.: NSString day = @"Tues";
result = 30 Aug
NSInteger desiredWeekday = 3; // Tuesday
NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;;
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
NSInteger currentWeekday = dateComponents.weekday;
NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
NSDateComponents *daysComponents = [[NSDateComponents alloc] init];
daysComponents.day = differenceDays;
NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:[NSDate date] options:0];
NSLog(@"newDate: %@", newDate);
2011-08-30 18:42:09.443 Test[63789:707] newDate: 2011-09-05 22:42:09 +0000
精彩评论