You may like this answer, I went with a LazyList[_]
since you probably don’t always want the whole thing in memory, I believe the above iterator
solutions do the same. I also decorated it a bit so that you can use either LocalDate
, LocalDateTime
, or ZonedDateTime
. I am using asInstanceOf
, which I rarely use, and everyone should rarely use, but since I am casting to the same thing, I found no harm, correct me if I am mistaken.
Anyway, try this:
import java.time._
import java.time.temporal._
case class DateRange[T <: Temporal](from:T, to:T) {
def every(i:Int, chronoUnit:ChronoUnit)(implicit ord:Ordering[T]):LazyList[T] =
LazyList.iterate(from)(t => t.plus(i, chronoUnit).asInstanceOf[T]).takeWhile(ord.lteq(_, to))
}
To use it, try some of these samples. Keep in mind, lazy lists would require using take
if you want some elements:
val result2 = DateRange(from = LocalDate.of(2010, 1, 10), to = LocalDate.of(2011, 3, 13)).every(3, ChronoUnit.DAYS)
val result3 = DateRange(from = LocalDateTime.of(2010, 1, 10, 12, 0, 1), to = LocalDateTime.of(2011, 3, 13, 13, 4, 50)).every(3, ChronoUnit.DAYS)
val result4 = DateRange(from = ZonedDateTime.of(2010, 1, 10, 12, 0, 1, 0, ZoneId.of("America/Los_Angeles")), to = ZonedDateTime.of(2011, 3, 13, 13, 4, 50, 0, ZoneId.of("America/Denver"))).every(1, ChronoUnit.YEARS)
println(result2.take(10).toList)
println(result3.take(10).toList)
println(result4.take(10).toList)
I hope you really enjoy Scala. 