title: java timestamps calculate overlap duration with interval
body: <p>I have many timestamps (<code>start, end</code>) which define an interval and want to efficiently check if they overlap another single interval. If yes, compute overlap duration, otherwise return 0.</p>
  
  <p>interval: <code>18:00</code> same day until <code>08:00</code> the next day. </p>
  
  <pre><code>start                  | end
  2018-01-02 14:59:18.922|2018-01-02 14:59:38.804
  2018-01-02 18:32:59.348|2018-01-02 20:30:41.192
  2018-01-02 01:54:59.363|2018-01-02 01:54:59.363
  2018-01-03 00:10:38.831|2018-01-03 00:11:53.103
  </code></pre>
  
  <p>I am unsure how to efficiently define <em>the next day</em> efficiently.</p>
  
  <h1>edit</h1>
  
  <pre><code>LocalDate
  </code></pre>
  
  <p>has a method <code>toInterval().overlaps(anotherInterval)</code>. I simply am unsure how to get fitting interval (18:00 - 08:00 next day) in a <strong>generic</strong> way, i.e. without manually reading the <code>YYYMMDD</code> and then creating a new object.</p>
  
  <ul>
  <li>a bit similar is <a href="https://stackoverflow.com/questions/38810914/find-if-hours-ranges-overlap-regardless-of-the-date/38817479#38817479">Find if hours ranges overlap regardless of the date</a></li>
  </ul>
  
  <h2>edit 2</h2>
  
  <p><code>toInterval</code> is only present for jodatime - not <code>java.time</code> / JSR-310. What would be a viable way to calculate overlap duration with java.time? </p>
  
  <p><a href="https://i.stack.imgur.com/mjQbx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mjQbx.png" alt="https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap"></a></p>
  
  <h2>edit3</h2>
  
  <p>A solution with jodaTime:</p>
  
  <pre><code>val begin = new DateTime(new java.sql.Timestamp().getTime())
  val stop = new DateTime(new java.sql.Timestamp().getTime())
  val i1 = new Interval(begin, stop)
  
  val start = new DateTime(begin.year.get   , begin.monthOfYear.get, begin.dayOfMonth.get, startHour, 0, 0, 0);
  val endIntermediate =stop.toDateTime.plusDays(1)
  val end = new DateTime(endIntermediate.year.get   , endIntermediate.monthOfYear.get, endIntermediate.dayOfMonth.get, endHour, 0, 0, 0);
  val i2 = new Interval(start, end)
  
  val overlap = i1.overlap(i2)
  val overlapDurationOrNull = overlap.toDuration
  </code></pre>
  
  <p>seems to work, but still is clumsy.</p>