patternMinor
Construct date sequence in Scala
Viewed 0 times
constructscaladatesequence
Problem
I want to have a continuous date sequence like ['2014-01-01','2014-01-02', ...]
Then I define a stream to do that.
I get the sequence within range [start, end) by calling
Any better/simple solution to do this ?
Then I define a stream to do that.
def daySeq(start: Date): Stream[Date] = Stream.cons(start, daySeq(plusDays(start, 1)))I get the sequence within range [start, end) by calling
daySeq(from).takeWhile(_.getTime < to.getTime)Any better/simple solution to do this ?
Solution
I suggest using Joda-Time's
Assuming you only need to traverse the days once, use an
Example usage:
If you do need a lazily-evaluated list, then
LocalDate instead of Java's Date to represent dates without a time zone.Assuming you only need to traverse the days once, use an
Iterator instead of a Stream.def dayIterator(start: LocalDate, end: LocalDate) = Iterator.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)Example usage:
dayIterator(new LocalDate("2013-10-01"), new LocalDate("2014-01-30")).foreach(println)If you do need a lazily-evaluated list, then
Stream is appropriate. I suggest using iterate instead of cons in that case.def dayStream(start: LocalDate, end: LocalDate) = Stream.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)Code Snippets
def dayIterator(start: LocalDate, end: LocalDate) = Iterator.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)dayIterator(new LocalDate("2013-10-01"), new LocalDate("2014-01-30")).foreach(println)def dayStream(start: LocalDate, end: LocalDate) = Stream.iterate(start)(_ plusDays 1) takeWhile (_ isBefore end)Context
StackExchange Code Review Q#44849, answer score: 7
Revisions (0)
No revisions yet.