如何使用Java从现在到最近三个小时获取任何随机时间

时间:2017-01-23 09:28:44

标签: java random time

任何人都可以告诉我如何使用 Java 1.7

在现在和最近三个小时之间获得任意随机时间

以下是我编写的用于生成随机数的行:

Random random = new Random();

for(int i =0; i<5; i++){
    int randomInteger = random.nextInt();
    System.out.println("Random Integer in Java: " + randomInteger);
}

但是如何在现在和最近三个小时之间获得任何随机时间?

2 个答案:

答案 0 :(得分:3)

以下情况如何?

    Date now = new Date();
    long timeRangeMs = 1000 * 60 * 60 * 3; // 3 hours in ms
    long random = ThreadLocalRandom.current().nextLong(timeRangeMs);
    Date randDate = new Date(now.getTime() - random);

答案 1 :(得分:1)

试试这个

public class RandomTime 
{
    public static void main(String[] args) 
    {
        Date d = new Date();
        System.out.println(d);

        Random r = new Random();
        int startTime = d.getMinutes();
        int endTime = low + 180;    // 3 hours
        int result = r.nextInt(endTime - startTime) + startTime;

        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        cal.add(Calendar.MINUTE, result);
        d.setMinutes(result);
        System.out.println(d);
    }
}