java隨機產生時間字串的方法,java產生字串

來源:互聯網
上載者:User

java隨機產生時間字串的方法,java產生字串

本文執行個體為大家分享了java隨機產生時間字串的具體代碼,供大家參考,具體內容如下

package com.wechat.utils;  import java.text.SimpleDateFormat; import java.util.Date;  /**  * Created by hexun on 2017/2/4.  */ public class RandTimeUtils {     /**    * 產生隨機時間    * @param beginDate    * @param endDate    * @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;    }    public static void main(String[] args){     Date randomDate=randomDate("2010-09-20","2017-02-04");     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     String resulttime = format.format(randomDate);//構造開始日期     System.out.println(resulttime);   } } 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.