gpt4 book ai didi

scala - 2个给定日期之间的随机日期

转载 作者:行者123 更新时间:2023-12-02 06:15:23 34 4
gpt4 key购买 nike

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

所以我有这个功能:

  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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com