당신은 두 단계로이 문제를 해결 할 수 있습니다
- 계산 최신 및 가장 빠른 시작 시간의 차이. 0과이 차이 사이의 임의의 값을 계산하고 가장 빠른 시작 시간에 추가하여 임의의 시작 시간을 얻으십시오.
- 임의 숫자로
Duration
을 만듭니다.이 숫자는 0-90 사이의 숫자입니다.
가
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;
}
}
출력은
,745,151이다
여기
이 예이다 (물론, 시작 시간이 듀레이션을 첨가하여 종료 시각을 산출한다)
startTime 2017-04-13T08:03:53Z
endTime 2017-06-01T08:03:53Z
duration 49 days
(참고 :이 예에서는 차이를 초 단위로 계산했습니다. 응용 프로그램의 경우에 따라 다른 단위 (예 : 하루 종일)를 사용하는 것이 좋습니다.
길이는 ms를 나타내는 int입니까? 초? 의사록? 뭐? – Catchwa
기간은 하루를 나타냅니다. 감사. – leo