如何使用NSDateComponents获取周三和周五的未来日期?答案将不胜感激。提前谢谢。
答案 0 :(得分:3)
如果你想让它完全防弹,这实际上是一个棘手的问题。我就是这样做的:
NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1)
NSInteger friday = 6;
NSDate *start = ...; // your starting date
NSDateComponents *components = [[NSDateComponents alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
for (int i = 0; i < 100; ++i) {
[components setDay:i];
NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0];
NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target];
if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) {
NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]);
}
}
[gregorian release];
[components release];
答案 1 :(得分:0)
要获得正确的星期几,您必须创建一个合适的NSCalendar实例,使用dateFromComponents创建一个NSDate对象:然后使用components:fromDate:来检索工作日。
答案 2 :(得分:0)
如果您有具体工作日(周三)的NSDate
实例,则可以使用以下代码获取新的未来日期:
NSDate *yourDate = ...
NSDateComponents* components = [[NSDateComponents alloc] init];
components.week = weeks;
NSDate* futureDate = [[NSCalendar reCurrentCalendar] dateByAddingComponents:components toDate:yourDate options:0];
[components release];
P.S。同意Brian,在询问前尝试研究。