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.
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
Note how above answer would lead to wrong result (total number of days is 117)
Iterate over specific dates between start and end
You may use
plusDays
:Given start and end dates:
For just iterating by day, I do:
This has proven to be useful enough that I have a small helper object to provide an implicit and allow for a type transformation:
Sample usage:
you can use something like that:
In this case, the
Scala way
is theJava way
:When running
Scala
onJava 9+
, we can usejava.time.LocalDate::datesUntil
:And if the last date is to be included:
Necessary import and initialization
Create List of
LocalDate
for sample durationIterate over specific dates between start and end using
toEpochDay
orgetLong(ChronoField.EPOCH_DAY)