package net.xiaof.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Random;
/**
* 日期工具类(生成指定年份范围内的一个日期)
*
* @author Tiger
* @date 2018-07-26
* @version v1.0
*/
public class DateUtil {
/**
* 生成指定年份范围内的一个日期[startYear,endYear]
*
* @since JDK8
* @param startYear
* 起始年份
* @param endYear
* 终止年份
* @return
*/
public static LocalDate getOneDateByYearRange(int startYear, int endYear) {
Random random = new Random();
int minDay = (int) LocalDate.of(startYear, 1, 1).toEpochDay();
int maxDay = (int) LocalDate.of(endYear, 1, 1).toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);
LocalDate randomDate = LocalDate.ofEpochDay(randomDay);
// LocalDate转为并Date返回
// ZoneId zone = ZoneId.systemDefault();
// Instant instant = randomDate.atStartOfDay().atZone(zone).toInstant();
// Date date = Date.from(instant);
return randomDate;
}
/**
* 生成指定年份范围内的一个日期[startYear,endYear]
*
* @since JDK6
* @param startYear
* 起始年份
* @param endYear
* 终止年份
* @return
*/
public static Date getOneDateByYearRange2(int startYear, int endYear) {
Random random = new Random();
GregorianCalendar gc = new GregorianCalendar();
int year = startYear + random.nextInt(endYear - startYear);
gc.set(Calendar.YEAR, year);
int month = random.nextInt(12)+1;
gc.set(Calendar.MONTH, month);
int day = random.nextInt(gc.getActualMaximum(Calendar.DAY_OF_MONTH))+1;//gc.getActualMaximum(Calendar.DAY_OF_MONTH),获取当前月份的最大天数
gc.set(Calendar.DAY_OF_YEAR, day);
return gc.getTime();
}
//测试
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(getOneDateByYearRange(1993, 2019)));
System.out.println(df.format(getOneDateByYearRange2(1993, 2019)));
}
}
Java生成指定年份范围内的一个日期
于 2020-07-26 23:39:49 首次发布