0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaで指定した期間内の日付・時間を列挙する

Posted at

https://stackoverflow.com/questions/30166507/iterate-over-dates-range-the-scala-way
ここに掲載されていたものを少し手直しした

main.scala
import org.joda.time._

object Main extends App {
  import IntervalIterators._

  val start = LocalDate.now().toDateTimeAtCurrentTime
  val end = LocalDate.now.plusDays(10).toDateTimeAtCurrentTime

  val interval = new Interval(start, end)
  interval.iterateByDay.foreach(println)
  interval.iterateByHour.foreach(println)
}

object IntervalIterators {
  implicit class ImplicitIterator(val interval: Interval) extends AnyVal {
    def iterateBy(step: Period): Iterator[DateTime] = Iterator.iterate(interval.getStart) { _.plus(step) }
      .takeWhile(_.isBefore(interval.getEnd))

    def iterateBy[A](step: Period, transform: DateTime => A): Iterator[A] = iterateBy(step).map(transform)

    def iterateByDay: Iterator[LocalDate] = iterateBy(Period.days(1), { _.toLocalDate })

    def iterateByHour: Iterator[DateTime] = iterateBy(Period.hours(1))
  }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?