- 要想产生指定范围内的随机日期,首先我们要指定一个范围,那么我们可以通过SImpleDateFormat格式化日期,然后再通过parse()方法设置日期,返回一个Date类型的日期对象,再转化为时间戳(long类型的),然后利用随机产生日期。
代码如下
public class Demo1 {
public static void main(String[] args) throws Exception {
Random r = new Random();
Date d = new Date();
long after = d.getTime(); //获取时间戳
//格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = "2022-05-01";
//开始解析时间
Date d2 = sdf.parse(str);
long before = d2.getTime();
long randomDate = (long) (before + (r.nextFloat() * (after - before + 1) ));
System.out.println(sdf.format(randomDate));
}
}
为减少代码复用率我们可以把产生随机日期写成一个方法,这样就可以反复调用了
public class Demo2 {
public static void main(String[] args) throws Exception {
//格式化时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//输入 随机起始时间
String str = "2022-05-10";
//解析时间
Date d1 = sdf.parse(str);
long before = d1.getTime();
//获取当前时间
Date d2 = new Date();
long after = d2.getTime();
long randomDate = randomLong(before,after);
System.out.println(sdf.format(randomDate));
}
public static long randomLong(long start, long end){
Random r = new Random();
return (long) (start + (r.nextFloat() * (end - start + 1)));
}
}



