2013-02-08 91 views

回答

10

在此之前相當嚴格的你問什麼(除了更正格式)。

Random random = new Random(); 

DateTime startTime = new DateTime(random.nextLong()).withMillisOfSecond(0); 

Minutes minimumPeriod = Minutes.TWO; 
int minimumPeriodInSeconds = minimumPeriod.toStandardSeconds().getSeconds(); 
int maximumPeriodInSeconds = Hours.ONE.toStandardSeconds().getSeconds(); 

Seconds randomPeriod = Seconds.seconds(random.nextInt(maximumPeriodInSeconds - minimumPeriodInSeconds)); 
DateTime endTime = startTime.plus(minimumPeriod).plus(randomPeriod); 

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); 

System.out.println(dateTimeFormatter.print(startTime)); 
System.out.println(dateTimeFormatter.print(endTime)); 

如果你運行它,你會注意到,你會得到離譜值多年,但是這只是在整個可能範圍的日期時間生成一個隨機的DateTime的結果(或日期爲此事) 。但是,如果需要,將限制結束時間限制到一定範圍的技術也可以應用於開始時間。

11

簡單

long rangebegin = Timestamp.valueOf("2013-02-08 00:00:00").getTime(); 
long rangeend = Timestamp.valueOf("2013-02-08 00:58:00").getTime(); 
long diff = rangeend - rangebegin + 1; 
Timestamp rand = new Timestamp(rangebegin + (long)(Math.random() * diff)); 
+1

這就生成只與日期1970-01-01不知道爲什麼一個隨機數。 – chettyharish 2013-02-08 12:23:49

+1

我認爲最後一行應該是'Timestamp rand = new Timestamp(rangebegin +(long)(Math.random()* diff));'' – saschoar 2014-04-15 13:40:46

1

基於一個事實,即任何日期可通過較長的數字來表示,採取Date類,http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#Date(long)的這個方法一看,你可以定義一個最大日期1,我們說今天,並隨機分配添加的分鐘數。

換句話說:

  • 步驟1 - 將隨機長數目或設置數爲日期1
  • 步驟2 - 隨機化分鐘加,乘隨機由58 分鐘(58×60 ×1000),並添加到日期1,再加上2分鐘(2× 60×1000)
1

嘗試

Random r = new Random(); 
    long t1 = System.currentTimeMillis() + r.nextInt(); 
    long t2 = t1 + 2 * 60 * 1000 + r.nextInt(60 * 1000) + 1; 
    DateTime d1 = new DateTime(t1); 
    DateTime d2 = new DateTime(t2); 
-2

您可以使用Math.random()生成一個隨機數; 您可以使用這項值