Iterate over dates range (the scala way)

后端 未结 7 1608
逝去的感伤
逝去的感伤 2021-02-04 10:26

Given a start and an end date I would like to iterate on it by day using a foreach, map or similar function. Something like

(DateTime.now to DateTime.now + 5.day         


        
7条回答
  •  渐次进展
    2021-02-04 11:07

    For just iterating by day, I do:

    Iterator.iterate(start) { _ + 1.day }.takeWhile(_.isBefore(end))
    

    This has proven to be useful enough that I have a small helper object to provide an implicit and allow for a type transformation:

    object IntervalIterators {
      implicit class ImplicitIterator(val interval: Interval) extends AnyVal {
        def iterateBy(step: Period): Iterator[DateTime] = Iterator.iterate(interval.start) { _ + step }
            .takeWhile(_.isBefore(interval.end))
    
        def iterateBy[A](step: Period, transform: DateTime => A): Iterator[A] = iterateBy(step).map(transform)
    
        def iterateByDay: Iterator[LocalDate] = iterateBy(1.day, { _.toLocalDate })
    
        def iterateByHour: Iterator[DateTime] = iterateBy(1.hour)
      }
    }
    

    Sample usage:

    import IntervalIterators._
    
    (DateTime.now to 5.day.from(DateTime.now)).iterateByDay // Iterator[LocalDate]
    
    (30.minutes.ago to 1.hour.from(DateTime.now)).iterateBy(1.second)  // Iterator[DateTime], broken down by second
    

提交回复
热议问题