Last active
January 29, 2020 21:43
-
-
Save lokkju/184e5815cd90699b6b33b96192c30714 to your computer and use it in GitHub Desktop.
Java 8/scala backport of datesUntil for iterating through dates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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