我想计算2个日期之间的随机日期。

所以我有这个功能:

  def calculateDates(from: LocalDate, until: LocalDate): Seq[LocalDate] =
  {
    val ld: LocalDate = new LocalDate()
    if (from.compareTo(until) > 1)
      return[]
    else
    return from :: calculateDates(from.plusDays(1), until)
  }

和我的投入:
01 Jan, 1970
01 Jan, 2015

因此,首先我需要更改函数以仅返回一个日期,第二件事是如何将输入转换为LocalDate对象?

最佳答案

为何不生成两个日期之间的所有日期并随机选择一个日期,为什么不计算两个日期之间的天数,选择该范围内的一个随机数,然后将天数加到第一个日期呢?

import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS
import scala.util.Random

def random(from: LocalDate, to: LocalDate): LocalDate = {
    val diff = DAYS.between(from, to)
    val random = new Random(System.nanoTime) // You may want a different seed
    from.plusDays(random.nextInt(diff.toInt))
}

scala> val from = LocalDate.of(1970, 1, 1)
from: java.time.LocalDate = 1970-01-01

scala> val to = LocalDate.of(2015, 1, 1)
to: java.time.LocalDate = 2015-01-01

scala> random(from, to)
res31: java.time.LocalDate = 2010-09-13

关于scala - 2个给定日期之间的随机日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35774504/

10-11 11:56