确定每周的星期。

时间:2022-11-29 18:55:43

Is it possible to do this:

是否有可能做到这一点:

Say I want to look at the week that is 12 weeks from today's date. How would I go about determining a specific date, say Tuesday of that week?

比如说,我想看看从今天开始的12周的一周。我如何确定一个具体的日期,比如那个星期的星期二?

Example:

例子:

I want to set a meeting up 6 weeks from now. I always have my meetings on Fridays. How would I get to that date?

我想从现在起6个星期后开个会。我总是在星期五开会。我该怎么去约会呢?

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 - weeks count, targetWeekday - number from 1 to 7 (1 - Sunday) which represents a day of the week.

每周数周数,目标工作日-数字从1到7(1 -周日),代表一周的一天。

resultDate - thursday after 6 weeks from current date

结果日期-从当前日期起6个星期后的星期四。

#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 - weeks count, targetWeekday - number from 1 to 7 (1 - Sunday) which represents a day of the week.

每周数周数,目标工作日-数字从1到7(1 -周日),代表一周的一天。

resultDate - thursday after 6 weeks from current date

结果日期-从当前日期起6个星期后的星期四。