gpt4 book ai didi

objective-c - 两个 NSDate 之间发生的特定工作日的计数

转载 作者:行者123 更新时间:2023-12-03 16:25:50 24 4
gpt4 key购买 nike

如何查找两个 NSDates 之间发生的特定工作日的计数?

我已经搜索了很长一段时间,但想出了唯一的解决方案,其中计算了总工作日数,而不仅仅是一个特定的工作日。

最佳答案

以下代码的想法是计算给定的第一次出现开始日期之后的工作日,然后计算剩余周数到结束日期。

NSDate *fromDate = ...;
NSDate *toDate = ...;
NSUInteger weekDay = ...; // The given weekday, 1 = Sunday, 2 = Monday, ...
NSUInteger result;

// Compute weekday of "fromDate":
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *c1 = [cal components:NSWeekdayCalendarUnit fromDate:fromDate];

// Compute next occurrence of the given weekday after "fromDate":
NSDateComponents *c2 = [[NSDateComponents alloc] init];
c2.day = (weekDay + 7 - c1.weekday) % 7; // # of days to add
NSDate *nextDate = [cal dateByAddingComponents:c2 toDate:fromDate options:0];

// Compare "nextDate" and "toDate":
if ([nextDate compare:toDate] == NSOrderedDescending) {
// The given weekday does not occur between "fromDate" and "toDate".
result = 0;
} else {
// The answer is 1 plus the number of complete weeks between "nextDate" and "toDate":
NSDateComponents *c3 = [cal components:NSWeekCalendarUnit fromDate:nextDate toDate:toDate options:0];
result = 1 + c3.week;
}

(代码假设一周有 7 天,这对于公历来说是正确的。如果有必要,代码可能可以推广到任意日历。)

关于objective-c - 两个 NSDate 之间发生的特定工作日的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17945062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com