需求:在开始日期与结束日期之间,每天在上午区间和下午区间内,各随机生成一条时间(时间间隔为10分钟)。
★参数
1.开始日期:startDate
2.结束日期:endDate
3.上午区间:
(1)上午开始时间:amStartTime
(2)上午结束时间:amEndTime
4.下午区间:
(1)下午开始时间:pmStartTime
(2)下午结束时间:pmEndTime
5.间隔时间:randomTime
1.获得指定日期范围内的每一天
List<Date> getRandomDateList(Date beginDate, Date endDate) throws ParseException {
List<Date> resList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf2= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date tmp = beginDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(beginDate);
String amStart = " 11:00:00";
String amEnd = " 12:30:00";
String pmStart = " 18:30:00";
String pmEnd = " 22:00:00";
while (tmp.getTime() < endDate.getTime()) {
tmp = calendar.getTime();
String format = sdf.format(tmp);
calendar.add(Calendar.DAY_OF_MONTH, 1);
String amStartFormat = format + amStart;
Date amStartDate = sdf2.parse(amStartFormat);
String amEndFormat = format + amEnd;
Date amEndDate = sdf2.parse(amEndFormat);
Date amRandomDate = getRandomDate(amStartDate, amEndDate);
resList.add(amRandomDate);
String pmStartFormat = format + pmStart;
Date pmStartDate = sdf2.parse(pmStartFormat);
String pmEndFormat = format + pmEnd;
Date pmEndDate = sdf2.parse(pmEndFormat);
Date pmRandomDate = getRandomDate(pmStartDate, pmEndDate);
resList.add(pmRandomDate);
}
return resList;
}
2.根据所传日期,在指定时间范围内,获得随机时间(10分钟间隔)
public Date getRandomDate(Date beginTime, Date endTime) {
Integer randomTime = 10;
List<Date> randomList = new ArrayList<>();
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(beginTime);
Date tmp2 = beginTime;
while (tmp2.getTime() < endTime.getTime()) {
tmp2 = calendar.getTime();
calendar.add(Calendar.MINUTE, randomTime);
randomList.add(tmp2);
}
Random random = new Random();
int index = random.nextInt(randomList.size());
return randomList.get(index);
}