2013-02-09 35 views
2

我想爲喬達時間創建一個種子點。我試圖實現的是,我將在Joda-Time中提供一個種子datetime,這應該會生成兩個不同的隨機datetime,使得在datetime2之前,並且此datetime將僅生成該種子點的特定小時的值。使用喬達時間種子,然後比較

例如

time- 18:00:00 followed by date-2013-02-13 

Random1 - 2013-02-13 18:05:24 

Random2 - 2013-02-13 18:48:22 

從一個數據庫收到時間並且用戶選擇日期。我需要以指定格式隨機生成兩次 您可以看到只有分鐘和秒會改變,沒有別的會被修改。

這可能嗎?我怎樣才能做到這一點?

回答

1

下面的代碼應該做你想做的。如果種子時間的分鐘或秒數可能​​不爲零,則應在.parseDateTime(inputDateTime)方法調用後添加.withMinuteOfHour(0).withSecondOfMinute(0)

import java.util.Random; 
import org.joda.time.DateTime; 
import org.joda.time.format.DateTimeFormat; 
import org.joda.time.format.DateTimeFormatter; 

public class RandomTime { 

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

public TwoRandomTimes getRandomTimesFromSeed(String inputDateTime) { 
    DateTime seed = inputFormat.parseDateTime(inputDateTime); 
    Random random = new Random(); 
    int seconds1 = random.nextInt(3600); 
    int seconds2 = random.nextInt(3600 - seconds1); 

    DateTime time1 = new DateTime(seed).plusSeconds(seconds1); 
    DateTime time2 = new DateTime(time1).plusSeconds(seconds2); 
    return new TwoRandomTimes(time1, time2); 
} 

public class TwoRandomTimes { 
    public final DateTime random1; 
    public final DateTime random2; 

    private TwoRandomTimes(DateTime time1, DateTime time2) { 
     random1 = time1; 
     random2 = time2; 
    } 

    @Override 
    public String toString() { 
     return "Random1 - " + outputFormat.print(random1) + "\nRandom2 - " + outputFormat.print(random2); 
    } 
} 

public static void main(String[] args) { 
    RandomTime rt = new RandomTime(); 
    System.out.println(rt.getRandomTimesFromSeed("18:00:00 2013-02-13")); 
} 
} 

在這個解決方案中,第一個隨機時間確實用作第二個隨機時間的下界。另一種解決方案是隻獲得兩個隨機日期,然後對它們進行排序。

+0

令人難以置信的工作,謝謝你通過減秒second獲得time2的想法從來沒有打到我的腦海。非常感謝你。 – chettyharish 2013-02-10 06:44:21

+0

@chettyharish我的榮幸。 :)只需檢查角落案件的執行情況和錯誤。例如,隨機時間可能相同,特別是如果第一次是18:59:59。 – ZeroOne 2013-02-12 07:06:18

0

我可能會用類似下面去:

final Random r = new Random(); 
final DateTime suppliedDate = new DateTime(); 
final int minute = r.nextInt(60); 
final int second = r.nextInt(60); 

final DateTime date1 = new DateTime(suppliedDate).withMinuteOfHour(minute).withSecondOfMinute(second); 
final DateTime date2 = new DateTime(suppliedDate).withMinuteOfHour(minute + r.nextInt(60 - minute)).withSecondOfMinute(second + r.nextInt(60 - second)); 

假設suppliedDate是從數據庫的日期。然後,根據您的種子時間,隨機生成兩個新的時間,分鐘和秒。您還可以保證第二次是在第一次之後通過改變計算的隨機數的邊界。