I work with an API where I need to write code to generate n appointment dates in the coming m months (from today). For the purpose, I write a Random date generator class provided. One condition is I need to use the java.sql.Date
for the class.
import java.sql.Date;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Objects;
import java.util.Random;
public class RandomDate {
private final Random random;
private final Date currentDate;
private final int months;
public RandomDate(Random random, Date currentDate, int months) {
this.random = random;
this.currentDate = currentDate;
this.months = months;
}
public Date getRangeEndDate() {
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(this.currentDate.getTime());
calendar.add(Calendar.DATE, this.months * 30);
return new Date(calendar.getTimeInMillis());
}
public Date generateRandomDate(Date endDate) {
int start = (int) this.currentDate.toLocalDate().toEpochDay();
int end = (int) endDate.toLocalDate().toEpochDay();
long randomDay = start + random.nextInt(end - start);
return Date.valueOf(LocalDate.ofEpochDay(randomDay));
}
}
I have an issue that within the code I use the time classes from 3 different packages (java.sql, java.time, and java.util). How can I write it more elegantly?
java.util
? \$\endgroup\$java.time.LocalDate
\$\endgroup\$java.sql.Date
? This requirement may be 20 years old. Current code usesjava.time.LocalDate
instead. \$\endgroup\$