4
\$\begingroup\$

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 ?

\$\endgroup\$
6
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

Any better/simple solution to do this ?

Yes. Functionality now built-in.

java.time.LocalDate::datesUntil ➙ Stream of LocalDate objects

The modern approach uses java.time classes.

The java.time.LocalDate has built-in support for generating a stream of dates. Call LocalDate::datesUntil.

I do not know Scala, so here is Java syntax.

LocalDate today = LocalDate.now ( ZoneId.of ( "Africa/Tunis" ) );
LocalDate later = today.plusDays ( 3 );
List < LocalDate > dates = today.datesUntil ( later ).collect ( Collectors.toUnmodifiableList () );

[2019-10-04, 2019-10-05, 2019-10-06]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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