How to create a list of random dates in Kotlin

1 Answer

0 votes
import java.time.LocalDate
import kotlin.random.Random

// Generate a random date between two years using LocalDate
fun 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.nextLong(startEpoch, endEpoch + 1)

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

fun main() {

    val dates = List(10) { randomDate(1990, 2030) }

    for (d in dates) {
        println("${d.year}-${d.monthValue}-${d.dayOfMonth}")
    }
}


/*
run:

2001-10-1
2001-12-23
2015-6-21
2004-10-27
2025-3-17
2001-11-7
2029-8-29
2002-4-26
2017-4-20
2019-5-5

*/

 



answered 15 hours ago by avibootz
...