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

前端 未结 6 1910
礼貌的吻别
礼貌的吻别 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 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)
    

提交回复
热议问题