简体   繁体   English

如何检查日期范围是否在Ruby中的另一个日期范围之间

[英]How to check if a date range is in between another date range in Ruby

So I have a date range which may be something like ((Date.today - 90)..Date.today) and I want to check to see whether (Date.today - 90) is after the first value in another date range, and Date.today is before the final value in a date range. 因此,我有一个日期范围,可能类似于((Date.today - 90)..Date.today) ,我想查看一下(Date.today - 90)是否在另一个日期范围的第一个值之后,而Date.today在日期范围内的最终值之前。 I've tried the following below 我在下面尝试了以下方法

((Date.parse('25-12-2000')..(Date.parse('25-12-2020')).include?((Date.today - 90)..Date.today)

This returns false. 这将返回false。 I also get false if I replace include? 如果我替换include?我也会得到假的include? with member? member? or cover? 还是cover?

How do I get this to return true? 我如何使它返回true? Syntax change or do I need to use a different method in Ruby? 语法更改还是我需要在Ruby中使用其他方法?

You could use cover? 你可以用cover? to check if the date range covers both values: 检查日期范围是否同时包含两个值:

range = Date.new(2000, 12, 25)..Date.new(2020, 12, 25)

range.cover?(Date.today - 90) && range.cover?(Date.today)
#=> true

or use begin and end if you have two ranges: 或使用beginend如果您有两个范围):

range = Date.new(2000, 12, 25)..Date.new(2020, 12, 25)
other = (Date.today - 90)..Date.today

range.cover?(other.begin) && range.cover?(other.end)
#=> true

I'd just check the first and last date against the range: 我只需要对照范围检查第一个和最后一个日期:

range = (Date.today - 90)..Date.today)
validation_range = ((Date.parse('25-12-2000')..(Date.parse('25-12-2020'))
range.first > validation_range && range.last < validation_range.last

You could break this down even further, rather just the first and last dates of each: 您可以进一步分解,而不仅仅是每个的开始和结束日期:

start_date = (Date.today - 90)
end_date = Date.today
start_validation = Date.parse('25-12-2000')
end_validation = Date.parse('25-12-2020')
start_date > start_validation && end_date < end_validation

I'm not sure the naming's ideal and you could trim this down to one line if you wanted, but hopefully this serves for illustrative purposes. 我不确定命名是否理想,如果需要,可以将其缩小为一行,但希望这能起到说明作用。 Also, you might want to use >= and <= though I'm not sure of whether the dates are inclusive. 另外,尽管我不确定日期是否包含在内,但您可能要使用>=<=

This would avoid any potentially expensive loops. 这样可以避免任何潜在的昂贵循环。

Hope that helps - let me know how you get on or if you have any questions! 希望对您有所帮助-让我知道您的生活状况或有任何疑问!

When you have two ranges A = (a..b) and B = (y..z) and want to know if B is fully covered by A then you can just ask if: 当您有两个范围A = (a..b)B = (y..z)并想知道B是否被A完全覆盖时,您可以问一下:

a <= y && z <= b

No need to build the ranges upfront. 无需预先建立范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM