确定给定周的星期几

时间:2013-11-06 21:39:39

标签: ios objective-c

是否可以这样做:

说我想看看从今天起12周后的一周。那个周的星期二,我该如何确定一个具体的日期呢?

示例:

我想在6周后召开会议。我总是在星期五举行会议。我怎么会到那个日期?

1 个答案:

答案 0 :(得分: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周后的星期四