两个给定日期之间的随机日期

时间:2016-03-03 14:12:10

标签: scala date random

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

所以我有这个功能:

  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对象?

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

LocalDate.ofEpochDay(from.toEpochDay + Random.nextInt((to.toEpochDay - from.toEpochDay) toInt))

答案 2 :(得分:1)

Scala 2.13开始,scala.util.Random提供between(minInclusive: Long, maxExclusive: Long)并与LocalDate::toEpochDay组合:

import scala.util.Random
import java.time.LocalDate

// val start = LocalDate.of(2019, 1, 20)
// val end   = LocalDate.of(2019, 2, 12)
LocalDate.ofEpochDay(Random.between(start.toEpochDay, end.toEpochDay))
// LocalDate = 2019-01-26

请注意,最后一个日期已排除在外。为了包括它:

LocalDate.ofEpochDay(Random.between(start.toEpochDay, end.toEpochDay + 1))