思考:
怎么用java实现随机生成时间?
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Test {
public static void main(String[] args) throws ParseException {
//随机生成日期和时间
DateTime randomDateTime = randomDateTime("2018-11-27 10:00:00","2018-11-28 12:00:00");
System.out.println(randomDateTime);
//DateTime ---> String
String dateStr = randomDateTime.toString("yyyy-MM-dd HH:mm:ss");
System.out.println(dateStr);
System.out.println("-----------------------------------------");
//只随机生成当天固定时间段的时间(日期+时间)
DateTime day = new DateTime();
//System.out.println(day);
DateTime randomDateTime2 = randomDateTime(day.toString("yyyy-MM-dd")+" 06:00:00", day.toString("yyyy-MM-dd")+" 11:00:00");
System.out.println(randomDateTime2);
//DateTime ---> String --->Date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date2 = sdf.parse(randomDateTime2.toString("yyyy-MM-dd HH:mm:ss"));
System.out.println(date2);
System.out.println("-----------------------------------------");
//只随机生成时间
DateTime randomTime = randomTime("10:00:00","12:00:00");
System.out.println(randomTime);//没有添加日期,则默认为"1970-01-01"
System.out.println(randomTime.toString().substring(11, 19));
}
/**
* 在[beginStr,endStr]生成随机日期+时间
* @param beginStr
* @param endStr
* @return
*/
public static DateTime randomDateTime(String beginStr,String endStr){
try {
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime beginTime = DateTime.parse(beginStr, format);
DateTime endTime = DateTime.parse(endStr, format);
if (beginTime.getMillis() > endTime.getMillis()) {
return null;
}
long randDateTime = random(beginTime.getMillis(), endTime.getMillis());
return new DateTime(randDateTime);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 在[beginStr,endStr]只随机生成时间,不包含日期
* 在没有添加日期格式时,默认为1970-01-01
* @param beginStr
* @param endStr
* @return
*/
public static DateTime randomTime(String beginStr,String endStr){
try {
DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm:ss");
DateTime beginTime = DateTime.parse(beginStr, format);
DateTime endTime = DateTime.parse(endStr, format);
if (beginTime.getMillis() > endTime.getMillis()) {
return null;
}
long randDateTime = random(beginTime.getMillis(), endTime.getMillis());
return new DateTime(randDateTime);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 随机生成时间
* 使用Math.random()方法---返回一个在介于(0,1)的随机数
* @param begin
* @param end
* @return
*/
private static long random(long begin, long end) {
long rand = begin + (long)(Math.random()*(end - begin));
if (rand == begin || rand == end) {
return random(begin, end);
}
return rand;
}
}