Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I want to have a continuous date sequence like ['2014-01-01','2014-01-02', ...]

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 ?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I suggest using Joda-Time's 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)
share|improve this answer
    
iterate looks better and simpler –  jilen Mar 24 at 1:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.