Kotlin: Create a random date
Video: Kotlin: Create a random date by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin: Create a Random Date
Generating a random date in Kotlin can be useful for testing, simulations, or sample data creation. This example demonstrates how to create a random date between two given dates by converting them to milliseconds, generating a random long value within that range, and converting it back to a date.
Code
import java.time.LocalDate
import java.time.ZoneId
import java.util.concurrent.ThreadLocalRandom
fun randomDate(startInclusive: LocalDate, endExclusive: LocalDate): LocalDate {
// Convert LocalDate to epoch day (days since 1970-01-01)
val startEpochDay = startInclusive.toEpochDay()
val endEpochDay = endExclusive.toEpochDay()
// Generate a random day between start and end
val randomDay = ThreadLocalRandom.current().nextLong(startEpochDay, endEpochDay)
// Convert the random epoch day back to LocalDate
return LocalDate.ofEpochDay(randomDay)
}
fun main() {
val startDate = LocalDate.of(2020, 1, 1)
val endDate = LocalDate.of(2023, 1, 1)
val random = randomDate(startDate, endDate)
println("Random date between $startDate and $endDate: $random")
}
Key Points
- Use LocalDate.toEpochDay() to convert dates to a numeric range for random selection.
- ThreadLocalRandom.current().nextLong(start, end) generates a random long within a range efficiently.
- Convert the random epoch day back to LocalDate with LocalDate.ofEpochDay() for easy date manipulation.
- This approach ensures the random date falls within the specified start (inclusive) and end (exclusive) dates.