還是因為填充自建資料表需要,需要一定範圍内的随機日期,目标是優雅簡潔高效.
思路有二:
- 生成一個符合要求的13位随機數作為毫秒,将毫秒轉化為java.sql包中的Date類
- 生成随機的年月,再根據年月确定日的範圍,生成随機日.
先上代碼,随後進行效率對比.
指定範圍為2016年-2018年(即2016年1月1日起-2018年12月31日止)
生成十三位随機數的方法:
public static Date randomHireday() {
int startYear=2016; //指定随機日期開始年份
int endYear=2018; //指定随機日期開始年份(含)
long start = Timestamp.valueOf(startYear+1+"-1-1 0:0:0").getTime();
long end = Timestamp.valueOf(endYear+"-1-1 0:0:0").getTime();
long ms=(long) ((end-start)*Math.random()+start); //獲得了符合條件的13位毫秒數
Date hireday=new Date(ms);
return hireday;
}
循環十次:

分别生成随機的年月日:
public static Date randomHireday2() {
int startYear=2016;
int endYear=2018;
int year = (int)(Math.random()*(endYear-startYear+1))+startYear; //随機年
int month= (int)(Math.random()*12)+1; //随機月
Calendar c = Calendar.getInstance(); //建立Calendar對象
c.set(year, month, 0); //設定日期
int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); //擷取對應年月有幾天
int day=(int)(Math.random()*dayOfMonth+1) ; //産生随機日
Date hireday=Date.valueOf(year+"-"+month+"-"+day); //通過valueOf方法生成Date對象
return hireday;
}
循環十次:
現在開始測試效率,分别做10次短測試和100000次長測試:
public static void main(String[] args) {
//随機十三位數
long start;
long end;
start = System.currentTimeMillis();
for(int i=0;i<10;i++) {
randomHireday();
}
end = System.currentTimeMillis();
System.out.println("随機十三位數10次循環所用時間:"+(end-start));
start = System.currentTimeMillis();
for(int i=0;i<100000;i++) {
randomHireday();
}
end = System.currentTimeMillis();
System.out.println("随機十三位數100000次循環所用時間:"+(end-start));
//分别随機生成年月日
start = System.currentTimeMillis();
for(int i=0;i<10;i++) {
randomHireday2();
}
end = System.currentTimeMillis();
System.out.println("分别随機生成年月日10次循環所用時間:"+(end-start));
start = System.currentTimeMillis();
for(int i=0;i<100000;i++) {
randomHireday2();
}
end = System.currentTimeMillis();
System.out.println("分别随機生成年月日100000次循環所用時間:"+(end-start));
}
顯然較為簡潔優雅的十三位随機數法的效率更高.
由此可見我們得到了優雅簡潔高效的随機日期生成方法.
友情連結:
自動生成指定長度的英文名字
https://blog.csdn.net/a755199443/article/details/88768538