1년 간격으로 임의의 시간 가져오기
다음 메소드는 연도를 입력 매개변수로 사용하고 지정된 연도 범위에서 임의의 시간을 리턴할 수 있습니다. 리턴된 시간 형식은 문자열 yyyy-mm-dd 형식입니다.
public String getRandomTime(int startYear, int endYear) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
//生成随机时间的年份
int year = (int) (Math.random() * (endYear - startYear + 1)) + startYear;
//生成随机时间的月份
int month = (int) (Math.random() * 12) + 1;
//使用Calendar对象确定生成的年份中的月份有多少天
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, 0);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
//生成随机时间的天
int day = (int) (Math.random() * dayOfMonth) + 1;
//将生成的时间格式化为yyyy-mm-dd格式
Date randomTime = dateFormat.parse(year + "-" + month + "-" + day);
return dateFormat.format(randomTime);
}
테스트 결과는 다음과 같습니다.
10년 [2019, 2021]년 간격에 대한 임의 시간 생성:
public static void main(String[] args) throws ParseException {
for (int i=0;i<10;i++){
String randomTime = getRandomTime(2019, 2021);
System.out.println(randomTime);
}
}