Find dates between two dates scala

Viewed 2397

I am trying to extract dates between two dates.

If my input is:

  • start date: 2020_04_02
  • end date: 2020_06_02

Output should be:

List("2020_04_02","2020_04_03", "2020_04_04", "2020_04_05", "2020_04_06")

So far i have tried:

val beginDate = LocalDate.parse(startDate, formatted)
val lastDate = LocalDate.parse(endDate, formatted)
beginDate.datesUntil(lastDate.plusDays(1))
  .iterator()
  .asScala
  .map(date => formatter.format(date))
  .toList

import java.time.format.DateTimeFormatter
private def formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd")

But i think it could be done even in a more refined way

3 Answers

I'm not super proud of this, but I've done it this way before:

import java.time.LocalDate

val start = LocalDate.of(2020,1,1).toEpochDay
val end = LocalDate.of(2020,12,31).toEpochDay
val dates = (start to end).map(LocalDate.ofEpochDay(_).toString).toArray

You end up with:

dates: Array[String] = Array(2020-01-01, 2020-01-02, ..., 2020-12-31)

What you are doing is correct but your end date is not matching what you are expecting:


    import java.time.format.DateTimeFormatter
    import java.time.LocalDate
    import scala.jdk.CollectionConverters._

    private def formatter = DateTimeFormatter.ofPattern("yyyy_MM_dd")
    val startDate = "2020_04_02"
    val endDate1 = "2020_04_06" // "2020_06_02"
    val endDate2 = "2020_06_02"
    val beginDate = LocalDate.parse(startDate, formatter)
    val lastDate1 = LocalDate.parse(endDate1, formatter)
    val lastDate2 = LocalDate.parse(endDate2, formatter)
    val res1 =  beginDate.datesUntil(lastDate1.plusDays(1)).iterator().asScala.map(date => formatter.format(date)).toList
    val res2 =  beginDate.datesUntil(lastDate2.plusDays(1)).iterator().asScala.map(date => formatter.format(date)).toList

    println(res1) // List(2020_04_02, 2020_04_03, 2020_04_04, 2020_04_05, 2020_04_06)
    println(res2) // List(2020_04_02, 2020_04_03, 2020_04_04, 2020_04_05, 2020_04_06 ... 2020_05_31, 2020_06_01, 2020_06_02)


This function will return List[String].

import java.time.format.DateTimeFormatter
import java.time.LocalDate

  val dt1 = "2020_04_02"
  val dt2 = "2020_04_06"

  def DatesBetween(startDate: String,endDate: String) : List[String] = {
    def ConvertToFormat = DateTimeFormatter.ofPattern("yyyy_MM_dd")
    val sdate = LocalDate.parse(startDate,ConvertToFormat)
    val edate = LocalDate.parse(endDate,ConvertToFormat)
    val DateRange = sdate.toEpochDay.until(edate.plusDays(1).toEpochDay).map(LocalDate.ofEpochDay).toList
    val ListofDateRange = DateRange.map(date => ConvertToFormat.format(date)).toList
    ListofDateRange
  }

  println(DatesBetween(dt1,dt2))
Related