2 dollar 20 cents 2 dollar 20 cents - 1 month ago 7
Java Question

Random generate a date which is after the date in string format

I got a question regarding the random generated date. So what I am trying to do is I random generate a day between 1-30, month between 1-12 and year by default is 2016.

Random rand = new Random();
int date = 1 + rand.nextInt((30 - 1) + 1);
int month = 1 + rand.nextInt((12 - 1) + 1);
if(month == 1){
monthStr = "January";
}else if(month == 2){
monthStr = "February";
}else if(month == 3){
monthStr = "March";
}else if(month == 4){
monthStr = "April";
}else if(month == 5){
monthStr = "May";
}else if(month == 6){
monthStr = "June";
}else if(month == 7){
monthStr = "July";
}else if(month == 8){
monthStr = "August";
}else if(month == 9){
monthStr = "September";
}else if(month == 10){
monthStr = "October";
}else if(month == 11){
monthStr = "November";
}else if(month == 12){
monthStr = "December";
}


I used a for loop to random generate the date for 100 times. Then, I append the string together to store it into a string array list.

ArrayList<String> dateTimeList = new ArrayList<String>();
dateTimeList.add(date + " " + monthStr + " 2016");


After that, I pass the entire list into another method. In this method, I am trying to generate again random date but in this case, I need to generate a date which is after the above one.

In another word, the first time when I random generated 100 dates is for the filing date. Then I pass in the entire list into another method, inside that method, I need to generate another 100 dates which is after each filing date.

Any ideas how could I achieve this? I know there is some other way to generate a random date but I preferred to be in this way as I will be using it in some other places.

Thanks in advance.

Answer

I assume you're using the latest Java with new Date API.

First create the earliest acceptable date, for example:

LocalDate baseDate = LocalDate.now(); //use today, OR
LocalDate baseDate = LocalDate.of(2016, 11, 30); //use any date - you can randomize the year/month/date if you want

Next, select a random number. Note, that you can add days or months or years to your date - this number should represent one of those. Let's assume days.

Integer maximumRandomValue = 100; //we want to add a number of days between 0-100
Integer randomDays = (int)(maximumRandomValue*Math.random());

Now just add them to your base date:

LocalDate randomDate = baseDate.plusDays(randomDays);

Also, if you want to convert it to String (although your database code should be able to handle that for you) here is a simple way (using the format as you provided in question)

String dateAsString = DateTimeFormatter.ofPattern("d MMMM yyyy").format(randomDate);

For more options on the format, please refer to API docs of DateTimeFormatter.