日期范围与其他日期范围的重叠 [英] Overlap of a Date Range with Other Date Ranges
问题描述
晚上好,
我想弄清楚如何通过比较日期范围来计算日期范围之间的天数.例如,我有三个给定的范围:
I am trying to figure out how to count the number of days between date ranges by comparing the date ranges. For example, I have three given ranges:
range_1 01/01/2001 to 01/01/2002
range_2 01/02/2002 to 01/01/2003
range_3 01/02/2003 to 01/01/2004
如果我将 my_date_range 12/12/2001 和 01/05/2002 与上述范围进行比较,结果应该显示 range_1 和 my_date_range 之间有 19 天,range_2 和 my_date_range 之间有 5 天,range_3 和my_date_range 有 0 天.
If I compare my_date_range 12/12/2001 to 01/05/2002 with the ranges above, the result should show that between range_1 and my_date_range there are 19 days, between range_2 and my_date_range there are 5 days, and between range_3 and my_date_range there are 0 days.
在 Excel 中这很容易,我会简单地使用:
In Excel this was easy, I would simply use:
=SUMPRODUCT(ISNUMBER(MATCH(ROW(INDIRECT(A1&":"&B1)),ROW(INDIRECT($C$1&":"&$D$1)),0))*1)
其中 A1 和 B1 是用户输入的开始日期和结束日期,C1 和 D1 是三个日期范围之一.然后我会使用相同的公式并将 A1 和 B1 与第二个日期范围进行比较,然后是第三个.
where A1 and B1 are the start and end dates the user enters, and C1 and D1 is one of the three date ranges. I would then use the same formula and compare A1 and B1 to the second date range, then the third.
但是这怎么翻译成objective-c呢?(我能够比较两个日期并获得它们之间的天数.)
But how is this translated into objective-c? (I am able to compare two dates and get the number of days between them.)
推荐答案
首先,您必须将日期字符串转换为 NSDate
值:
First you have to convert the date strings to NSDate
values:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];
NSDate *range1Start = [dateFormatter dateFromString:@"01/01/2001"];
NSDate *range1End = [dateFormatter dateFromString:@"01/01/2002"];
NSDate *userStart = [dateFormatter dateFromString:@"12/12/2001"];
NSDate *userEnd = [dateFormatter dateFromString:@"01/05/2002"];
然后你可以计算重叠间隔:
Then you can compute the overlapping interval:
NSDate *overlapFrom = [range1Start laterDate:userStart];
NSDate *overlapTo = [range1End earlierDate:userEnd];
最后是重叠间隔的开始日期和结束日期之间的天数:
And finally the number of days between the start and end date of the overlapping interval:
NSInteger days;
if ([overlapFrom compare:overlapTo] > 0) {
// Date ranges do not overlap
days = 0;
} else {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:NSDayCalendarUnit fromDate:overlapFrom toDate:overlapTo options:0];
days = [comp day];
}
NSLog(@"%ld", (long)days);
在此示例中,输出为 20
,因为 12/12/2001 和 01/01/2002 之间的差异是 20 天.如果要计算重叠范围的开始和结束日期,则必须添加 1
.
In this example, the output is 20
, because the difference between 12/12/2001 and 01/01/2002 is 20 days. You have to add 1
if both start and end day of the overlapping range should be counted.
这篇关于日期范围与其他日期范围的重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!