Joda DateTime重叠和过滤

时间:2015-09-22 16:07:25

标签: scala jodatime

我有两个间隔说,

// for simplicity, I present here only the hours
val interval1 = (08, 20)
val interval2 = (00, 10)

现在,当我在两个间隔之间重叠时,我得到了

val overlap = interval.overlap(interval2) // gives me (08, 10)

我可以使用joda-time中的方法来获取非重叠时间段吗?我需要得到(10,20)

我尝试使用间隙方法:

scala> val a = new Interval(DateTime.parse("2000-10-12T00:00:00"), DateTime.parse("2000-10-12T20:00:00"))

scala> val b = new Interval(DateTime.parse("2000-09-12T00:00:00"), DateTime.parse("2000-10-12T12:00:00"))

a.gap(b) // returns null
b.gap(a) // returns null

1 个答案:

答案 0 :(得分:1)

看起来库中没有提供此功能的内容。所以我想出了我自己的实现,就像这样:

  private def splitIntervals(interval1: Interval, interval2: Interval) = {
    Option(interval1.overlap(interval2)) match {
      case Some(overlap) => {
        if (overlap.equals(interval1)) Seq(interval1)
        else if (overlap.equals(interval2))
          Seq(overlap) :+
            new Interval(interval1.getStart, overlap.getStart) :+
            new Interval(overlap.getEnd, interval1.getEnd)
        else if (overlap.getStart.equals(interval1.getStart))
          Seq(overlap) :+
            new Interval(overlap.getEnd, interval1.getEnd)  
        else Seq(overlap) :+
          new Interval(interval1.getStart, overlap.getEnd)
      }
      case _ => Seq(interval1)
    }
  }

它涵盖了所有可能的边缘情况!