从Scala中不在timeDuration列表中的一天获取所有timeDuration

时间:2016-03-28 12:23:51

标签: list scala timestamp

我有一个List((startTime,endTime))形式的时间戳元组列表,它们基本上表示一整天的时间段。

例如:

(("2016-03-28 14:00:00","2016-03-28 15:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 21:00:00"), 
 ("2016-03-28 01:00:00","2016-03-28 13:00:00"))

我想获得此列表中的持续时间列表。

所以输出应该是:

(("2016-03-28 00:00:00","2016-03-28 01:00:00"),
 ("2016-03-28 13:00:00","2016-03-28 14:00:00"),
 ("2016-03-28 15:00:00","2016-03-28 17:00:00"),
 ("2016-03-28 17:00:00","2016-03-28 24:00:00"))

有人能建议在Scala中使用这种方法吗?

到目前为止,我尝试过的天真解决方案如下:

import java.sql.Timestamp
import scala.collection.mutable.ListBuffer

def comparator(first: (Timestamp,Timestamp), second: (Timestamp, Timestamp)) = first._2.getTime <= second._1.getTime

val data = List((Timestamp.valueOf("2016-03-28 00:00:00"),Timestamp.valueOf("2016-03-28 10:00:00")),
  (Timestamp.valueOf("2016-03-28 12:00:00"),Timestamp.valueOf("2016-03-28 15:00:00")),
  (Timestamp.valueOf("2016-03-28 23:00:00"),Timestamp.valueOf("2016-03-28 23:59:59")),
  (Timestamp.valueOf("2016-03-28 16:00:00"),Timestamp.valueOf("2016-03-28 21:00:00"))
).sortWith(comparator)

var emptySlots = new ListBuffer[(Timestamp,Timestamp)]()
var currTime = Timestamp.valueOf("2016-03-28 00:00:00")
var index = 0
var cond = 0
while(cond == 0){

  if (currTime.compareTo(Timestamp.valueOf("2016-03-28 23:59:59")) < 0 && index >= data.size){
    emptySlots += ((currTime,Timestamp.valueOf("2016-03-28 23:59:59") ))
    cond = 1
  }
  else if(index >= data.size)
  {
    cond = 1
  }
  else if(currTime.compareTo(data(index)._1) < 0) {
    emptySlots += ((currTime, data(index)._1))
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) >= 0 && currTime.compareTo(data(index)._2) < 0 ) {
    currTime = data(index)._2
    index += 1
  }
  else if(currTime.compareTo(data(index)._1) > 0 && currTime.compareTo(data(index)._2) > 0 ) {

    index += 1
  }

}

emptySlots.toList

0 个答案:

没有答案