Iterate over dates range (the scala way)

后端 未结 7 1585
逝去的感伤
逝去的感伤 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

    This answer fixes the issue of mrsrinivas answer, that .get(ChronoUnits.DAYS) returns only the days part of the duration, and not the total number of days.

    Necessary import and initialization

    import java.time.temporal.ChronoUnit
    import java.time.{LocalDate, Period}
    

    Note how above answer would lead to wrong result (total number of days is 117)

    scala> Period.between(start, end)
    res6: java.time.Period = P3M26D
    
    scala> Period.between(start, end).get(ChronoUnit.DAYS)
    res7: Long = 26
    

    Iterate over specific dates between start and end

    val start = LocalDate.of(2018, 1, 5)
    val end   = LocalDate.of(2018, 5, 1)
    
    // Create List of `LocalDate` for the period between start and end date
    
    val dates: IndexedSeq[LocalDate] = (0L to (end.toEpochDay - start.toEpochDay))
      .map(days => start.plusDays(days))
    
    dates.foreach(println)
    

提交回复
热议问题