Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a range, getting all dates within that range in Scala

Tags:

date

loops

scala

I need to make a function in scala that, given a range of dates, gives me a list of the range. I am relatively new in Scala and I am not able to figure out how to write the right 'for' loop for the same. This is what I have done so far:

def calculateDates(from: LocalDate, until: LocalDate): Seq[LocalDate] = {
  var dateArray = []
  //for (LocalDate date <- from; !date.isAfter(to); date <- date.plusDays(1)) 
  for(date <- from to until)
  {
        dateArray :+ date
  }
  return dateArray 
} 

I do not know how to iterate over the range.

like image 806
Core_Dumped Avatar asked Oct 17 '13 12:10

Core_Dumped


4 Answers

If you happen to use the Java 1.8 DateTime API (or its 1.7 backport threeten), then you could write

def between(fromDate: LocalDate, toDate: LocalDate) = {
    fromDate.toEpochDay.until(toDate.toEpochDay).map(LocalDate.ofEpochDay)
} 
like image 128
sandris Avatar answered Oct 19 '22 03:10

sandris


val numberOfDays = Days.daysBetween(from, until).getDays()
for (f<- 0 to numberOfDays) yield from.plusDays(f)
like image 44
Ashalynd Avatar answered Oct 19 '22 04:10

Ashalynd


Try this

def dateRange(start: DateTime, end: DateTime, step: Period): Iterator[DateTime] =
Iterator.iterate(start)(_.plus(step)).takeWhile(!_.isAfter(end))

To generate every date, you can set the step to 1 day like

val range = dateRange(
<yourstartdate>,
<yourenddate>,
Period.days(1))
like image 7
jester Avatar answered Oct 19 '22 02:10

jester


When running Scala on Java 9+, we can take advantage of the new java.time.LocalDate::datesUntil:

import java.time.LocalDate
import collection.JavaConverters._

// val start = LocalDate.of(2018, 9, 24)
// val end   = LocalDate.of(2018, 9, 28)
start.datesUntil(end).iterator.asScala.toList
// List[LocalDate] = List(2018-09-24, 2018-09-25, 2018-09-26, 2018-09-27)

And to include the last date within the range:

start.datesUntil(end.plusDays(1)).iterator.asScala.toList
// List[LocalDate] = List(2018-09-24, 2018-09-25, 2018-09-26, 2018-09-27, 2018-09-28)
like image 6
Xavier Guihot Avatar answered Oct 19 '22 02:10

Xavier Guihot