Iterate over dates range (the scala way)

后端 未结 7 1586
逝去的感伤
逝去的感伤 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
    慢半拍i (楼主)
    2021-02-04 11:05

    Solution with java.time API using Scala

    Necessary import and initialization

    import java.time.temporal.ChronoUnit
    import java.time.temporal.ChronoField.EPOCH_DAY
    import java.time.{LocalDate, Period}
    
    val now = LocalDate.now
    val daysTill = 5
    

    Create List of LocalDate for sample duration

    (0 to daysTill)
      .map(days => now.plusDays(days))
      .foreach(println)
    

    Iterate over specific dates between start and end using toEpochDay or getLong(ChronoField.EPOCH_DAY)

    //Extract the duration
    val endDay = now.plusDays(daysTill)
    val startDay = now
    
    val duration = endDay.getLong(EPOCH_DAY) - startDay.getLong(EPOCH_DAY)
    
    /* This code does not give desired results as trudolf pointed
    val duration = Period
      .between(now, now.plusDays(daysTill))
      .get(ChronoUnit.DAYS)
    */
    
    //Create list for the duration
    (0 to duration)
      .map(days => now.plusDays(days))
      .foreach(println)
    

提交回复
热议问题