先上代码:
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class test {
private static Date randomDate(String beginDate, String endDate){
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date start = format.parse(beginDate);
Date end = format.parse(endDate);
if(start.getTime() >= end.getTime()){
return null;
}
long date = random(start.getTime(),end.getTime());
return new Date(date);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static long random(long begin,long end){
long rtn = begin + (long)(Math.random() * (end - begin));
if(rtn == begin || rtn == end){
return random(begin,end);
}
return rtn;
}
public static void main(String[] args) {
//获取当前时间
String nowDateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime nowDate = LocalDateTime.parse(nowDateStr, formatter);
//获取当前时间的前3小时
LocalDateTime minusHoursThree = nowDate.minusHours(3);
String minusHoursDateThree = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(minusHoursThree);
//获取当前时间的前24小时
LocalDateTime minusHoursTwfour = nowDate.minusHours(24);
String minusHoursDateTwfour = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(minusHoursTwfour);
//获取 当前时间 前3到24小时内的随机时间
Date date = randomDate(minusHoursDateTwfour,minusHoursDateThree);
String randomDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println("当前时间:" + nowDateStr);
System.out.println("当前时间前3到24小时内的随机时间:" + randomDate);
}
}
这里是获取当前时间前3小时到24小时内的一个随机时间。
执行结果:
这个LocalDateTime时间类很强大,也可以获取当前时间之前或之后的几分钟、几小时、几天、几周、几月、几年。方法很多。可以用相应的方法获取一个时间点之前或之后任意时间段的随机时间。