Skip to content

Instantly share code, notes, and snippets.

@sscarduzio
Created December 9, 2014 10:24
Show Gist options
  • Save sscarduzio/9d20d2ccd7a69161f51d to your computer and use it in GitHub Desktop.
Save sscarduzio/9d20d2ccd7a69161f51d to your computer and use it in GitHub Desktop.
[@tailrec] Split time interval in smaller interval (Scala and Joda Time)
import org.joda.time.format.DateTimeFormat
import org.joda.time._
import scala.annotation.tailrec
val timeWindow: Seconds = Seconds.seconds(Hours.hours(12).toStandardSeconds.getSeconds)
type Delta = (DateTime, DateTime)
def splitInterval(from: DateTime, to: DateTime, interval: Seconds): Seq[Delta] = {
@tailrec
def loop(_from: DateTime, intervalList: Seq[Delta]): Seq[Delta] = {
_from match {
case f if f.isAfter(to) => intervalList
case f => {
val fplus1 = f.plus(timeWindow)
loop(fplus1, intervalList ++ Seq((f, fplus1)))
}
}
}
// We don't want the last split (I hate this glitch)
loop(from, Seq()).dropRight(1)
}
// Note: probably there's a way to do this in one line in JodaTime :D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment