您可以分兩步解決這個問題:
- 計算最新的最早開始時間之間的區別。計算0這種差異之間的隨機值,並將它添加到的最早開始時間,以獲得一個隨機的開始時間
- 從一個隨機數天,在這個數字是0和90之間,你的情況創建
Duration
(當然,添加此持續時間加到開始時間將產生結束時刻)
下面是一個例子:
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Random;
public class RandomOffsetDateTimeRange
{
public static void main(String[] args)
{
OffsetDateTime earliestStartTime =
OffsetDateTime.parse("2017-04-01T00:00:00+00:00");
OffsetDateTime latestStartTime =
OffsetDateTime.parse("2017-05-31T23:59:59+00:00");
int maxDays = 90;
Random random = new Random(0);
OffsetDateTime startTime =
computeRandomOffsetDateTime(
earliestStartTime, latestStartTime, random);
Duration duration = randomDaysDuration(maxDays, random);
OffsetDateTime endTime = startTime.plus(duration);
System.out.println("startTime " + startTime);
System.out.println("endTime " + endTime);
System.out.println("duration " + duration.toDays() + " days");
}
private static Duration randomDaysDuration(int maxDays, Random random)
{
int days = random.nextInt(maxDays);
return Duration.ofDays(days);
}
private static OffsetDateTime computeRandomOffsetDateTime(
OffsetDateTime min, OffsetDateTime max, Random random)
{
long differenceInSeconds = min.until(max, ChronoUnit.SECONDS);
long seconds = nextLong(random, differenceInSeconds);
return min.plusSeconds(seconds);
}
// From https://stackoverflow.com/a/2546186/3182664
private static long nextLong(Random rng, long n) {
// error checking and 2^x checking removed for simplicity.
long bits, val;
do {
bits = (rng.nextLong() << 1) >>> 1;
val = bits % n;
} while (bits-val+(n-1) < 0L);
return val;
}
}
輸出是
startTime 2017-04-13T08:03:53Z
endTime 2017-06-01T08:03:53Z
duration 49 days
(注:在該實例中,我計算以秒爲單位的差異。根據應用程序的情況下,您可能需要使用不同的單元,例如,整個天)
是持續時間較毫秒一個int?秒?分鐘?什麼? – Catchwa
持續時間代表一天。謝謝。 – leo