Java怎麼產生隨機日期__Java

來源:互聯網
上載者:User

import java.text.SimpleDateFormat; import java.util.Date; public class DateRandomTest { // 返回2007-01-01到2007-03-01的一個隨機日期 public static void main(String[] args) { Date randomDate = randomDate("2007-01-01", "2007-03-01"); System.out.println(randomDate.toString()); } /** * 擷取隨機日期 * * @param beginDate * 起始日期,格式為:yyyy-MM-dd * @param endDate * 結束日期,格式為:yyyy-MM-dd * @return */ private 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; } private 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; } }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.