Obtain random date

Source: Internet
Author: User

<Br> import java. text. parseexception; <br> import java. text. simpledateformat;
Import java. util. date;
Public class getrandomtiem {<br> // return a random date from.
Public static void main (string [] args) {<br> simpledateformat format = new simpledateformat ("hh: mm: ss "); <br> date randomdate = randomdate ("00:00:00", "24:59:59"); <br> string randomdats = "shi" + randomdate. gethours () + "f" + randomdate. getminutes () + "m" + randomdate. getseconds (); <br> system. out. println (randomdats );
}
/**
* Obtain a random date
* @ Param begindate start date. Format: yyyy-mm-dd
* @ Param enddate: end date, in the format of yyyy-mm-dd
* @ Return
*/
Private static date randomdate (string begindate, string enddate ){
Try {
Simpledateformat format = new simpledateformat ("hh: mm: ss ");
Date start = format. parse (begindate); // construct the start date
Date end = format. parse (enddate); // construct the end date
// Gettime () indicates the number of milliseconds that the date object represents since January 1, 1970 00:00:00 gmt.
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 start time and end time are returned, recursively call this function to find the random value.
If (rtn = begin | rtn = end) {<br> return random (begin, end );
}
Return rtn;
}
}

Author: "My java blog"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.