Rails: calculate how many days overlap between two date ranges

okay, let's say we have three date ranges.

1. date1=01-20-2015..02-15-2015
2. date2 = 01-01-2015..01-31-2015
3. date3 = 02-01-2015..02-28-2015

      

I need a way to calculate how many days between date1 and date2 overlap (10 days in this case). and how many days between date1 and date3 overlap (15 days in this case)?

Is there an easy way to calculate this?

+3


source to share


1 answer


If you have:

r1= (Date.new(2015, 01, 20))..(Date.new(2015, 2, 15))
r2= (Date.new(2015, 01, 1))..(Date.new(2015, 1, 31))

      

You can check the intersection this way:



r1.to_a & r2.to_a
=> [Tue, 20 Jan 2015,
 Wed, 21 Jan 2015,
 Thu, 22 Jan 2015,
 Fri, 23 Jan 2015,
 Sat, 24 Jan 2015,
 Sun, 25 Jan 2015,
 Mon, 26 Jan 2015,
 Tue, 27 Jan 2015,
 Wed, 28 Jan 2015,
 Thu, 29 Jan 2015,
 Fri, 30 Jan 2015,
 Sat, 31 Jan 2015]

      

The cost of converting ranges to arrays though

You may notice (r1.to_a & r2.to_a).count #=> 12

rather than 10

, but it also depends on whether or not you include boundaries.

+1


source







All Articles