Skip to content

Instantly share code, notes, and snippets.

@lokkju
Last active January 29, 2020 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lokkju/184e5815cd90699b6b33b96192c30714 to your computer and use it in GitHub Desktop.
Save lokkju/184e5815cd90699b6b33b96192c30714 to your computer and use it in GitHub Desktop.
Java 8/scala backport of datesUntil for iterating through dates
import java.time.temporal.{ChronoUnit, Temporal, TemporalAmount}
import java.time.{Duration, Period}
import scala.concurrent.duration.FiniteDuration
object DatesUntilImplicits {
implicit class DatesUntilExtensions[T <: Temporal with Comparable[_]](val start: T) {
def datesUntil(end: T, step: TemporalAmount): Iterator[T] = {
Iterator.iterate(start) {
_.plus(step).asInstanceOf[T]
}
.takeWhile(_.asInstanceOf[ Comparable [ T ] ].compareTo(end) < 0)
}
def datesUntil(end: T, step: FiniteDuration): Iterator[T] =
datesUntil(end, java.time.Duration.of(step.toMillis, ChronoUnit.MILLIS))
def yearsUntil(end: T): Iterator[T] = datesUntil(end, Period.ofYears(1))
def monthsUntil(end: T): Iterator[T] = { datesUntil(end, Period.ofMonths(1)) }
def daysUntil(end: T): Iterator[T] = datesUntil(end, Period.ofDays(1))
def hoursUntil(end: T): Iterator[T] = datesUntil(end, Duration.ofHours(1))
def minutesUntil(end: T): Iterator[T] = datesUntil(end, Duration.ofMinutes(1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment