0

是否有可能做到这一点:

假设我想查看距今天日期 12 周的那一周。我将如何确定一个具体的日期,比如那周的星期二?

例子:

我想在 6 周后安排一次会议。我总是在星期五开会。我怎样才能到达那个日期?

4

1 回答 1

0
NSInteger numberOfWeeksToAdd = 6;
NSInteger targetWeekday = 5; // thursday

NSDate *today = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.week = numberOfWeeksToAdd;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *futureDate = [calendar dateByAddingComponents:comps toDate:today options:0];
NSDateComponents *futureDateComps = [calendar components:NSCalendarUnitWeekday fromDate:futureDate];

NSInteger weekday = futureDateComps.weekday;
NSDateComponents *c = [[NSDateComponents alloc] init];
c.day = targetWeekday - weekday;

NSDate *resultDate = [calendar dateByAddingComponents:c toDate:futureDate options:0];

numberOfWeeksToAdd - 周数,targetWeekday - 从 1 到 7(1 - 星期日)的数字,代表一周中的某一天。

resultDate - 从当前日期起 6 周后的星期四

于 2013-11-06T22:18:00.517 回答