java's method of randomly generating time strings

  • 2020-12-07 04:02:21
  • OfStack

This article is an example for you to share java random generation of time string specific code, for your reference, specific content is as follows


package com.wechat.utils; 
 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
/** 
 * Created by hexun on 2017/2/4. 
 */ 
public class RandTimeUtils { 
 
 
  /** 
   *  Generating random time  
   * @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);// Construction start date  
 
      Date end = format.parse(endDate);// End date of construction  
 
      //getTime() Represents return from  1970  years  1  month  1  day  00:00:00 GMT  Since the  Date  The number of milliseconds the object represents.  
 
      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 and end times are returned, this function is recursively called to find random values  
 
    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);// Construction start date  
    System.out.println(resulttime); 
  } 
} 


Related articles: