Iterate over dates range (the scala way)

后端 未结 7 1610
逝去的感伤
逝去的感伤 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条回答
  •  旧时难觅i
    2021-02-04 11:09

    In this case, the Scala way is the Java way:

    When running Scala on Java 9+, we can use java.time.LocalDate::datesUntil:

    import java.time.LocalDate
    import collection.JavaConverters._
    
    // val start = LocalDate.of(2019, 1, 29)
    // val end   = LocalDate.of(2018, 2,  2)
    start.datesUntil(end).iterator.asScala
    // Iterator[java.time.LocalDate] =  (2019-01-29, 2019-01-30, 2019-01-31, 2019-02-01)
    

    And if the last date is to be included:

    start.datesUntil(end.plusDays(1)).iterator.asScala
    // 2019-01-29, 2019-01-30, 2019-01-31, 2019-02-01, 2019-02-02
    

提交回复
热议问题