在 Java 中获取一天中随机时间戳的数量

Getting number of random timestamps throughout a day in Java

解决这个问题的好方法是什么?我希望在一天中随机显示一条消息 5 次。我目前使用以下方法生成时间戳:

List<Long> timestamps = new ArrayList<Long>();

long currentTimestamp = (long) (System.currentTimeMillis() / 1000L);
long endTimestamp = addHoursToTimestamp(8, currentTimestamp);

int n_timestamps = 5;
for (int i = 0; i < n_timestamps; i++) {
    Long randomTime = currentTimestamp + Math.abs(new Random().nextLong()) % (endTimestamp-currentTimestamp);
    timestamps.add(randomTime);
}

有时这很管用,我可以很好地分散时间戳。当然,正如您所想象的那样,有时时间戳彼此非常接近,例如在本例中,第 11 个小时有 3 个时间戳(在 11:00-19:00 的时间跨度内):

1435483835  Sun Jun 28 11:30:35 CEST 2015
1435501808  Sun Jun 28 16:30:08 CEST 2015
1435484646  Sun Jun 28 11:44:06 CEST 2015
1435495886  Sun Jun 28 14:51:26 CEST 2015
1435483799  Sun Jun 28 11:29:59 CEST 2015

这并不理想,因为我希望时间戳稍微分散一些。为了解决这个问题,我创建了一个函数,它循环遍历已经添加到数组中的所有时间戳,并检查生成的时间戳是否至少比每个时间戳晚或早一个小时。

但是,我不知道这是否是解决问题的首选方法。计算量好像挺大的。

我会像这样为每个均匀间隔的时间段生成一个随机时间:

List<Long> timestamps = new ArrayList<Long>();
long currentTimestamp = (long) (System.currentTimeMillis() / 1000L);

int hourRange = 8;    
int n_timestamps = 5;
double timePeriod = hourRange / (n_timestamps + 0.0);
Random rand = new Random();

for (int i = 0; i < n_timestamps; i++) {
    long startTimestamp = addHoursToTimestamp(i, currentTimestamp);
    long endTimestamp = addHoursToTimestamp(timePeriod, startTimestamp);

    Long randomTime = startTimestamp + Math.abs(rand.nextLong()) % (endTimestamp-startTimestamp);
    timestamps.add(randomTime);
}

因此对于 8 小时的时间段,将为 1h36m 的 5 个时间段中的每个时间段生成一个随机时间。

只需确保 addHoursToTimeStamp() 可以接受 double 值。