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

前端 未结 6 1864
礼貌的吻别
礼貌的吻别 2021-02-04 03:29

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 righ

相关标签:
6条回答
  • 2021-02-04 03:59

    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)
    } 
    
    0 讨论(0)
  • 2021-02-04 03:59

    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))
    
    0 讨论(0)
  • 2021-02-04 04:00
    val numberOfDays = Days.daysBetween(from, until).getDays()
    for (f<- 0 to numberOfDays) yield from.plusDays(f)
    
    0 讨论(0)
  • 2021-02-04 04:00

    Use Lamma Date

    $ scala -cp lamma_2.11-1.1.2.jar 
    Welcome to Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> import io.lamma.Date
    import io.lamma.Date
    
    scala> Date(2015, 7, 7) to Date(2015, 7, 10) foreach println 
    Date(2015,7,7)
    Date(2015,7,8)
    Date(2015,7,9)
    Date(2015,7,10)
    

    This DateRange is evaluated in a lazy way. Feel free to construct a date range of 5000 years. :)

    0 讨论(0)
  • 2021-02-04 04:13

    Since Scala is a functional, go with a recursion:

    def calculateDates(from: LocalDate, until: LocalDate): Seq[LocalDate] = {
        if from.compareTo(until) > 1
            return[]
        else
            return from :: calculateDates(from.plusDays(1), until)
    } 
    
    0 讨论(0)
  • 2021-02-04 04:14

    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)
    
    0 讨论(0)
提交回复
热议问题