1.获取两个时间
LocalDateTime startTime,
LocalDateTime endTime
2.将两个时间转为秒为单位的时间戳
long start = startTime.toEpochSecond(ZoneOffset.of("+8"));
long end = endTime.toEpochSecond(ZoneOffset.of("+8"));
3.计算两个时间戳的差值
long difference = (long)(Math.random() * (end - start));
4.生成随机时间
LocalDateTime.ofEpochSecond(start+difference,0, ZoneOffset.ofHours(8))
完整代码
public class DateRandomTools {
/**
* 一个时间段内随机一个时间
* @param startTime
* @param endTime
* @return
*/
public static LocalDateTime createRandomDate(LocalDateTime startTime, LocalDateTime endTime){
//将两个时间转为时间戳
long start = startTime.toEpochSecond(ZoneOffset.of("+8"));
long end = endTime.toEpochSecond(ZoneOffset.of("+8"));
//获取两个时间的随机数
long difference = (long)(Math.random() * (end - start));
//生成时间
return LocalDateTime.ofEpochSecond(start+difference,0, ZoneOffset.ofHours(8));
}
/**
* 一个时间段内随机一个时间
* @param startTime
* @param endTime
* @param number
* @return
*/
public static List<LocalDateTime> createRandomDate(LocalDateTime startTime, LocalDateTime endTime,Integer number){
//将两个时间转为时间戳
long start = startTime.toEpochSecond(ZoneOffset.of("+8"));
long end = endTime.toEpochSecond(ZoneOffset.of("+8"));
long difference;
List<LocalDateTime> list = new ArrayList<>();
for (int i = 0; i < number; i++) {
//获取两个时间的随机数
difference = (long)(Math.random() * (end - start));
//生成时间
list.add(LocalDateTime.ofEpochSecond(start+difference,0, ZoneOffset.ofHours(8)));
}
return list;
}
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
List<LocalDateTime> localDateTimeList = createRandomDate(LocalDateTime.now(), LocalDateTime.now().plusHours(1L), 10);
for (LocalDateTime localDateTime : localDateTimeList) {
System.out.println(localDateTime.format(formatter));
}
}