如何生成唯一的日期范围

时间:2017-03-20 06:40:50

标签: scala

我想在当前日期之间生成唯一的日期范围,比如说2050。

val start_date = "2017-03-21"
val end_date = "2050-03-21"

不确定如何为它创建功能。请在此输入任何内容。开始日期和结束日期之间的差异可以是任何东西。

唯一的日期范围意味着该函数永远不会返回它已经返回的日期范围。

我有这个解决方案:

val start_date = "2017-03-21"

val end_date = "2050-03-21"


while(start_date= "2017-03-21")
{
end_date = start_date+1
return( start_date, end_date)

}

start_date=start_date+1 

1 个答案:

答案 0 :(得分:0)

我们将使用java.time.LocalDatetemporal.ChronoUnit导入来实现此目的:

scala> import java.time.LocalDate
import java.time.LocalDate

scala> import java.time.temporal.ChronoUnit
import java.time.temporal.ChronoUnit

scala> val startDate = LocalDate.parse("2017-03-21")
startDate: java.time.LocalDate = 2017-03-21

scala> val endDate = LocalDate.parse("2050-03-21")
endDate: java.time.LocalDate = 2050-03-21

scala> val dateAmount = 5
dateAmount: Int = 5

scala> val randomDates = List.fill(dateAmount) {
  val randomAmt = ChronoUnit.DAYS.between(startDate, endDate) * math.random() // used to generate a random amount of days within given limits
  startDate.plusDays(randomAmt.toInt) // returns a date from that random amount, will not go beyond endDate
}
randomDates: List[java.time.LocalDate] = List(2049-03-16, 2025-12-30, 2042-04-20, 2027-03-14, 2031-03-15)