Iterate over dates range (the scala way)

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

    You may use plusDays:

    val now = DateTime.now
    (0 until 5).map(now.plusDays(_)).foreach(println)
    

    Given start and end dates:

    import org.joda.time.Days
    
    val start = DateTime.now.minusDays(5)
    val end   = DateTime.now.plusDays(5)    
    
    val daysCount = Days.daysBetween(start, end).getDays()
    (0 until daysCount).map(start.plusDays(_)).foreach(println)
    

提交回复
热议问题