mercredi 2 décembre 2015

Random date generation with java.time

I'm writing some code to populate a MySQL database with random data for testing purposes. So far I had no problem with the String attributes but now I need to populate a DATE column with random dates from 1970-2015.

And I'm so lost with all those Date and Time and Calendar tools around.

Here's the relevant method:

public Date dateGenerator() throws Exception{
        Random ry = new Random();
        Random rm = new Random();
        Random rd = new Random();
        int year = 1969 + ry.nextInt(2015-1969+1);
        int month = 1 + rm.nextInt(12);
        int day = 1 + rm.nextInt(31);

        if (month==2 && day>28){
            day = day - 3;            
        }else{
            if((month%2==0 && month != 8 ) && day==31 ){
                day = day -1;
            }
        }

My purpose is to create three random integers (for day, month, year) and somehow combine them into some Date object to pass to the database. But the database rejects everything I try to feed it.

It would be very educational for me if you can supply me with a suggestion based in the newest java.time library if this is possible.

Your help is greatly appreciated :)




Aucun commentaire:

Enregistrer un commentaire