package com.showy.vo.rest; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { /** * 生成隨機時間 * * @param beginDate * @param endDate * @return */ public static Date randomDate(String beginDate, String endDate) { try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date start = format.parse(beginDate);// 構造開始日期 Date end = format.parse(endDate);// 構造結束日期 // getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以來此 Date 對象表示的毫秒數。 if (start.getTime() >= end.getTime()) { return null; } long date = random(start.getTime(), end.getTime()); return new Date(date); } catch (Exception e) { e.printStackTrace(); } return null; } public static long random(long begin, long end) { long rtn = begin + (long) (Math.random() * (end - begin)); // 如果返回的是開始時間和結束時間,則遞歸調用本函數查找隨機值 if (rtn == begin || rtn == end) { return random(begin, end); } return rtn; } public static String addTime(){ /** 開始時間 結束時間 */ Date randomDate = randomDate("2020-08-01", "2021-04-07"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String result = format.format(randomDate); return result; } }