开发者

Create next NSDate that matches day NSString

开发者 https://www.devze.com 2023-03-31 13:37 出处:网络
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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消