I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?
To generate random dates between two dates, you can use the RANDBETWEEN function, together with the DATE function. This formula is then copied down from B5 to B11. The result is random dates between Jan 1, 2016 and Dec 31, 2016 (random dates in the year 2016).
import java.util.GregorianCalendar; public class RandomDateOfBirth { public static void main(String[] args) { GregorianCalendar gc = new GregorianCalendar(); int year = randBetween(1900, 2010); gc.set(gc.YEAR, year); int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR)); gc.set(gc.DAY_OF_YEAR, dayOfYear); System.out.println(gc.get(gc.YEAR) + "-" + (gc.get(gc.MONTH) + 1) + "-" + gc.get(gc.DAY_OF_MONTH)); } public static int randBetween(int start, int end) { return start + (int)Math.round(Math.random() * (end - start)); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With