scaladatetimeiterationnscala-time

Iterate over dates range (the scala way)


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 by 1.day).foreach(println)

I am using https://github.com/nscala-time/nscala-time, but I get returned a joda Interval object if I use the syntax above, which I suspect is also not a range of dates, but a sort of range of milliseconds.

EDIT: The question is obsolete. As advised on the joda homepage, if you are using java 8 you should start with or migrate to java.time.


Solution

  • 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)