I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
If you don't mind adding a new library to your code you can use MockNeat (disclaimer: I am one of the authors).
Snippet for a Java 8 based solution:
Note: This generates a random date between 1Jan1900 (inclusive) and 1Jan2015 (exclusive).
Note: It is based on epoch days, i.e. days relative to 1Jan1970 (EPOCH) - positive meaning after EPOCH, negative meaning before EPOCH
You can also create a small utility class:
and use it like this:
I am studying Scala and ended up Googling Java solutions for choosing a random date between range. I found this post super helpful and this is my final solution. Hope it can help future Scala and Java programmers.
Look this method:
If you don't mind a 3rd party library, the Utils library has a RandomDateUtils that generates random java.util.Dates and all the dates, times, instants, and durations from Java 8's date and time API
It is in the Maven Central Repository at:
java.util.Date
has a constructor that accepts milliseconds since The Epoch, andjava.util.Random
has a method that can give you a random number of milliseconds. You'll want to set a range for the random value depending on the range of DOBs that you want, but those should do it.Very roughly: