在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
Generating random date in a specific range in JAVA
提问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.Date
with given range.
鉴于您的问题不清楚,我希望您尝试在java.util.Date
给定范围内生成随机数。
Please note that java.util.Date
contains date + time information.
请注意,java.util.Date
包含日期 + 时间信息。
Date
in 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);