tags:

views:

51

answers:

3

I'm trying to generate a random DOB for People in my database. In a java program, can some one help me?

+1  A: 

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);
T.J. Crowder
+1  A: 

You need to define a random date, right?

A simple way of doing that is to generate a new Date object, using a long (time in milliseconds since 1st January, 1970) and substract a random long:

new Date(Math.abs(System.currentTimeMillis() - RandomUtils.nextLong()));

(RandomUtils is taken from Apache Commons Lang).

Of course, this is far to be a real random date (for example you will not get date before 1970), but I think it will be enough for your needs.

Otherwise, you can create your own date by using Calendar class:

int year = // generate a year between 1900 and 2010;
int dayOfYear = // generate a number between 1 and 365 (or 366 if you need to handle leap year);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, randomYear);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
Date randomDoB = calendar.getTime();
romaintaz
A: 
import java.util.GregorianCalendar;


public class RandomDOB {

    public static void main(String[] args) {

        int year = RandomDOB.randBetween(1900, 2010);

        int month = RandomDOB.randBetween(0, 11);

        GregorianCalendar gc = new GregorianCalendar(year, month, 1);

        int day = RandomDOB.randBetween(1, gc.getActualMaximum(gc.DAY_OF_MONTH));

        gc.set(year, month, day);

        System.out.println(gc.get(gc.YEAR) + "-" + gc.get(gc.MONTH) + "-" + gc.get(gc.DAY_OF_MONTH));

    }


    public static int randBetween(int start, int end) {
        return start + (int)Math.round(Math.random() * (end - start));
    }
}
Saul