How to create a list of random dates in Scala

1 Answer

0 votes
import java.time.{LocalDate, ZoneOffset}
import java.time.temporal.ChronoUnit
import scala.util.Random

object RandomDates {

  // Generate a random date between two years using LocalDate
  def randomDate(startYear: Int, endYear: Int): LocalDate = {

    // Convert start and end years to timestamps
    val start = LocalDate.of(startYear, 1, 1)
    val end   = LocalDate.of(endYear, 12, 31)

    val startEpoch = start.toEpochDay
    val endEpoch   = end.toEpochDay

    // Uniform distribution over the timestamp range
    val randomEpoch = Random.between(startEpoch, endEpoch + 1)

    // Convert back to LocalDate
    LocalDate.ofEpochDay(randomEpoch)
  }

  def main(args: Array[String]): Unit = {

    val dates = (1 to 10).map(_ => randomDate(1990, 2030))

    for (d <- dates) {
      println(s"${d.getYear}-${d.getMonthValue}-${d.getDayOfMonth}")
    }
  }
}



/*
run:

2010-5-31
2024-4-8
2027-11-24
2028-1-27
1998-5-23
2023-2-24
2017-12-11
2012-2-3
2030-2-25
2024-12-12

*/

 



answered 16 hours ago by avibootz
...