Generate random date of birth

2019-01-04 12:21发布

I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?

标签: java random
12条回答
一夜七次
2楼-- · 2019-01-04 13:18

If you don't mind adding a new library to your code you can use MockNeat (disclaimer: I am one of the authors).

MockNeat mock = MockNeat.threadLocal();

// Generates a random date between [1970-1-1, NOW)
LocalDate localDate = mock.localDates().val();
System.out.println(localDate);

// Generates a random date in the past
// but beore 1987-1-30
LocalDate min = LocalDate.of(1987, 1, 30);
LocalDate past = mock.localDates().past(min).val();
System.out.println(past);

LocalDate max = LocalDate.of(2020, 1, 1);
LocalDate future = mock.localDates().future(max).val();
System.out.println(future);

// Generates a random date between 1989-1-1 and 1993-1-1
LocalDate start = LocalDate.of(1989, 1, 1);
LocalDate stop = LocalDate.of(1993, 1, 1);
LocalDate between = mock.localDates().between(start, stop).val();
System.out.println(between);
查看更多
别忘想泡老子
3楼-- · 2019-01-04 13:21

Snippet for a Java 8 based solution:

Random random = new Random();
int minDay = (int) LocalDate.of(1900, 1, 1).toEpochDay();
int maxDay = (int) LocalDate.of(2015, 1, 1).toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);

LocalDate randomBirthDate = LocalDate.ofEpochDay(randomDay);

System.out.println(randomBirthDate);

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:

public class RandomDate {
    private final LocalDate minDate;
    private final LocalDate maxDate;
    private final Random random;

    public RandomDate(LocalDate minDate, LocalDate maxDate) {
        this.minDate = minDate;
        this.maxDate = maxDate;
        this.random = new Random();
    }

    public LocalDate nextDate() {
        int minDay = (int) minDate.toEpochDay();
        int maxDay = (int) maxDate.toEpochDay();
        long randomDay = minDay + random.nextInt(maxDay - minDay);
        return LocalDate.ofEpochDay(randomDay);
    }

    @Override
    public String toString() {
        return "RandomDate{" +
                "maxDate=" + maxDate +
                ", minDate=" + minDate +
                '}';
    }
}

and use it like this:

RandomDate rd = new RandomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2010, 1, 1));
System.out.println(rd.nextDate());
System.out.println(rd.nextDate()); // birthdays ad infinitum
查看更多
beautiful°
4楼-- · 2019-01-04 13:21

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.

import java.sql.Timestamp

def date_rand(ts_start_str:String = "2012-01-01 00:00:00", ts_end_str:String = "2015-01-01 00:00:00"): String = {
    val ts_start = Timestamp.valueOf(ts_start_str).getTime()
    val ts_end = Timestamp.valueOf(ts_end_str).getTime()
    val diff = ts_end - ts_start
    println(diff)
    val ts_rand = new Timestamp(ts_start + (Random.nextFloat() * diff).toLong)
    return ts_rand.toString
}                                         //> date_rand: (ts_start_str: String, ts_end_str: String)String

println(date_rand())                      //> 94694400000
                                              //| 2012-10-28 18:21:13.216

println(date_rand("2001-01-01 00:00:00", "2001-01-01 00:00:00"))
                                              //> 0
                                              //| 2001-01-01 00:00:00.0
println(date_rand("2001-01-01 00:00:00", "2010-01-01 00:00:00"))
                                              //> 283996800000
                                              //| 2008-02-16 23:15:48.864                    //> 2013-12-21 08:32:16.384
查看更多
神经病院院长
5楼-- · 2019-01-04 13:24

Look this method:

public static Date dateRandom(int initialYear, int lastYear) {
    if (initialYear > lastYear) {
        int year = lastYear;
        lastYear = initialYear;
        initialYear = year;
    }

    Calendar cInitialYear = Calendar.getInstance();
    cInitialYear.set(Calendar.YEAR, 2015);
    long offset = cInitialYear.getTimeInMillis();

    Calendar cLastYear = Calendar.getInstance();
    cLastYear.set(Calendar.YEAR, 2016);
    long end = cLastYear.getTimeInMillis();

    long diff = end - offset + 1;
    Timestamp timestamp = new Timestamp(offset + (long) (Math.random() * diff));
    return new Date(timestamp.getTime());
}
查看更多
Viruses.
6楼-- · 2019-01-04 13:24

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

LocalDate birthDate = RandomDateUtils.randomPastLocalDate();
LocalDate today = LocalDate.now();
LocalDate under18YearsOld = RandomDateUtils.randomLocalDate(today.minus(18, YEARS), today);
LocalDate over18YearsOld = RandomDateUtils.randomLocalDateBefore(today.minus(18, YEARS));

It is in the Maven Central Repository at:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>
查看更多
虎瘦雄心在
7楼-- · 2019-01-04 13:25

java.util.Date has a constructor that accepts milliseconds since The Epoch, and java.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:

Random  rnd;
Date    dt;
long    ms;

// Get a new random instance, seeded from the clock
rnd = new Random();

// Get an Epoch value roughly between 1940 and 2010
// -946771200000L = January 1, 1940
// Add up to 70 years to it (using modulus on the next long)
ms = -946771200000L + (Math.abs(rnd.nextLong()) % (70L * 365 * 24 * 60 * 60 * 1000));

// Construct a date
dt = new Date(ms);
查看更多
登录 后发表回答