随机生成一组指定范围内的日期
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 1, 1, 0, 0);
LocalDateTime end = LocalDateTime.of(2024, 10, 15, 17, 59);
long startTime = start.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
long endTime = end.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
List<LocalDateTime> dates = new ArrayList<>();
for (int i = 0; i < 10; i++) { // 生成10个随机日期
long randomTime = startTime + (long) (Math.random() * (endTime - startTime + 1));
LocalDateTime randomDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(randomTime), ZoneId.systemDefault());
dates.add(randomDate);
}
dates.forEach(item -> System.out.println(item.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
}
给指定的时间随机增加一段时间
public static void main(String[] args) {
// 示例时间数据
List<String> dates = Arrays.asList("2024-03-30 05:49:11",
"2024-08-20 12:53:09",
"2024-07-17 23:58:01");
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 处理每个日期时间,随机增加1-3天、0-23小时和0-59分钟
List<String> modifiedDates = new ArrayList<>();
ThreadLocalRandom current = ThreadLocalRandom.current();
for (String dateTimeStr : dates) {
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, formatter);
// 随机增加1到3天
int randomDays = current.nextInt(1, 4);
LocalDateTime modifiedDateTime = dateTime.plusDays(randomDays);
// 随机增加0到23小时
int randomHours = current.nextInt(0, 24);
modifiedDateTime = modifiedDateTime.plusHours(randomHours);
// 随机增加0到59分钟
int randomMinutes = current.nextInt(0, 60);
modifiedDateTime = modifiedDateTime.plusMinutes(randomMinutes);
modifiedDates.add(modifiedDateTime.format(formatter));
}
// 输出修改后的日期时间
System.out.println("原始日期时间: " + dates);
System.out.println("修改后的日期时间: " + modifiedDates);
}