在JAVA中生成特定范围内的随机日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40253332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:32:57  来源:igfitidea点击:

Generating random date in a specific range in JAVA

javaalgorithmdate

提问by Ashish Kumar

How to generate random dates in a specific range in JAVA? I have seen How do I generate random integers within a specific range in Java?link which is to generate random numbers.Is there similar/other kind of way to generate random date in JAVA?

如何在JAVA中生成特定范围内的随机日期?我已经看到如何在 Java 中生成特定范围内的随机整数?生成随机数的链接。在 JAVA 中是否有类似/其他类型的方法来生成随机日期?

采纳答案by Adrian Shum

Given that your question is unclear, I am expecting you are trying to generate random java.util.Datewith given range.

鉴于您的问题不清楚,我希望您尝试在java.util.Date给定范围内生成随机数。

Please note that java.util.Datecontains date + time information.

请注意,java.util.Date包含日期 + 时间信息。

Datein Java is represented by milliseconds from EPOCH. Therefore the easiest way to do what you want is, given d1 and d2 is Date, and d1 < d2 (in pseudo-code):

Date在 Java 中,以 EPOCH 中的毫秒数表示。因此,做你想做的最简单的方法是,给定 d1 和 d2 是Date,并且 d1 < d2 (在伪代码中):

Date randomDate = new Date(ThreadLocalRandom.current()
                              .nextLong(d1.getTime(), d2.getTime()));


If it is actually a "Date" (without time) that you want to produce, which is usually represented by LocalDate(in Java 8+, or using JODA Time).

如果它实际上是您想要生成的“日期”(没有时间),通常由LocalDate(在 Java 8+ 中,或使用 JODA 时间)表示。

It is as easy as, assume d1 and d2 being LocalDate, with d1 < d2(pseudo-code):

它就像假设 d1 和 d2 一样简单LocalDate,使用d1 < d2(伪代码):

int days = Days.daysBetween(d1, d2).toDays();
LocalDate randomDate = d1.addDays(ThreadLocalRandom.nextInt(days+1));

回答by Saravana

Try this

尝试这个

    LocalDate startDate = LocalDate.of(1990, 1, 1); //start date
    long start = startDate.toEpochDay();
    System.out.println(start);

    LocalDate endDate = LocalDate.now(); //end date
    long end = endDate.toEpochDay();
    System.out.println(start);

    long randomEpochDay = ThreadLocalRandom.current().longs(start, end).findAny().getAsLong();
    System.out.println(LocalDate.ofEpochDay(randomEpochDay)); // random date between the range

回答by ravthiru

You can do something like this

你可以做这样的事情

    long random = ThreadLocalRandom.current().nextLong(startDate.getTime(), endDate.getTime());
    Date date = new Date(random);