Reputation: 41
Need to format date according to yyyyMMdd below code generates a list of dates
import org.joda.time.LocalDate
import org.joda.time._
def getDates(startDate: String,endDate: String): Any = {
val from = LocaDate.parse(startDate)
val until = LocalDate.parse(endDate)
val numberOfDays = Days.daysBetween(from, until).getDays()
for (f<- 0 to numberOfDays) yield from.plusDays(f)
}
println(getDates("20200101","20200131"))
This returns -> Vector(2020-01-01,2020-01-31)
Need to convert returned Vector to List[String] in which elements are of format "yyyyMMdd"
Expected Output: List(20200101,....,20200131)
Upvotes: 1
Views: 710
Reputation: 51271
If the getDates()
input is 2 strings, and the desired output is List[String]
, then I don't really see any reason to use the old and outdated Joda Time library. The java.time
library is more recent and feature-full.
It also offers the datesUntil()
method, which does pretty much what you want, except that it returns a java.util.stream.Stream
, which is a bit of a pain because the transition from Java Stream
to Scala List
will depend on the Scala version you're running.
Here, for example, is how you might do it in Scala 2.13.x:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import scala.jdk.StreamConverters.StreamHasToScala
def getDates(startDate:String, endDate:String):List[String] = {
val pattern = DateTimeFormatter.ofPattern("yyyyMMdd")
LocalDate.parse(startDate, pattern)
.datesUntil(LocalDate.parse(endDate, pattern).plusDays(1))
.toScala(List)
.map(_.format(pattern))
}
You'll notice that there is no checking for valid input format, so this is for demonstration and not production-worthy code.
Upvotes: 2