如何生成随机的OffsetDateTime范围?

时间:2017-09-25 02:02:42

标签: java

我有:

OffsetDateTime earliestStartTime = 20170401T000000Z
OffsetDateTime latestStartTime = 20170531T235959Z

如何生成时间范围:

startTime is a random OffsetDateTime in [earliestStartTime .. latestStartTime];
Duration is a random int in [1 .. 90], representing number of Days.
endTime is startTime + Duration.

我没有" com.pholser.junit.quickcheck.random.SourceOfRandomness",因此无法使用SourceOfRandomness。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以分两步解决此问题:

  • 计算最新和最早开始时间之间的差异。计算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;
     }    
}

输出

startTime 2017-04-13T08:03:53Z
endTime   2017-06-01T08:03:53Z
duration  49 days

(注意:在示例中,我计算了以秒为单位的差异。根据您的应用案例,您可能希望使用不同的单位,例如,整天)