创建与NSString匹配的下一个NSDate

时间:2011-08-30 11:58:53

标签: iphone

我想创建一个NSDate对象,表示第二天与NSString日匹配。

例如。 NSString是MON或星期一我想获得与今天相匹配的下一个NSDate - 今天也是如此。

例如:NSString day = @“Tues”;

结果= 8月30日

1 个答案:

答案 0 :(得分:2)

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测试[63789:707] newDate:2011-09-05 22:42:09 +0000