我使用的API需要编写代码以在未来n
个月(从今天开始)中生成m
个约会日期。为此,我编写了一个随机日期生成器类。
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));
}
}
代码看起来不错,我们可以更优雅地做到吗?
答案 0 :(得分:2)
不,这看起来不太好,因为您使用的是来自3个不同程序包(java.sql,java.time和java.util)的时间类。
您应该只使用java.time类,然后将结果转换为所需的内容(打印,持久化...)。
答案 1 :(得分:0)
我仅使用java.time.LocalDate
public class RandomDate {
private final LocalDate today;
private final Random random;
private final int months;
public RandomDate(Random random, int months) {
this.today = LocalDate.now();
this.random = random;
this.months = months;
}
public LocalDate getRangeEndDate() {
LocalDate rangeEndDay = this.today.plusDays(this.months * 30);
return rangeEndDay;
}
public LocalDate generateRandomDate(LocalDate endDate) {
int start = (int) this.today.toEpochDay();
int end = (int) endDate.toEpochDay();
long randomDay = start + random.nextInt(end - start);
return LocalDate.ofEpochDay(randomDay);
}
public LocalDate getToday() {
return today;
}
public Random getRandom() {
return random;
}
public int getMonths() {
return months;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RandomDate)) return false;
RandomDate that = (RandomDate) o;
return getMonths() == that.getMonths() &&
Objects.equals(getToday(), that.getToday()) &&
Objects.equals(getRandom(), that.getRandom());
}
@Override
public int hashCode() {
return Objects.hash(getToday(), getRandom(), getMonths());
}
@Override
public String toString() {
return "RandomDate{" +
"today=" + today +
", random=" + random +
", months=" + months +
'}';
}}