Generating Random Date time in java (joda time)

↘锁芯ラ 提交于 2019-12-18 21:54:13

问题


Is it possible to generate a random datetime using Jodatime such that the datetime has the format yyyy-MM-dd HH:MM:SS and it should be able to generate two random datetimes where Date2 minus Date1 will be greater than 2 minutes but less than 60minutes. Please suggest some method.


回答1:


This follows quite strictly what you asked for (except for the corrected format).

Random random = new Random();

DateTime startTime = new DateTime(random.nextLong()).withMillisOfSecond(0);

Minutes minimumPeriod = Minutes.TWO;
int minimumPeriodInSeconds = minimumPeriod.toStandardSeconds().getSeconds();
int maximumPeriodInSeconds = Hours.ONE.toStandardSeconds().getSeconds();

Seconds randomPeriod = Seconds.seconds(random.nextInt(maximumPeriodInSeconds - minimumPeriodInSeconds));
DateTime endTime = startTime.plus(minimumPeriod).plus(randomPeriod);

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

System.out.println(dateTimeFormatter.print(startTime));
System.out.println(dateTimeFormatter.print(endTime));

If you run this, you'll note that you'll get outrageous values for years, but that's simply the consequence of generating a random DateTime over the entire possible range of DateTime (or Date for that matter). But the same technique of limiting the end time to a certain range can be applied to the start time if you want.




回答2:


Simple

long rangebegin = Timestamp.valueOf("2013-02-08 00:00:00").getTime();
long rangeend = Timestamp.valueOf("2013-02-08 00:58:00").getTime();
long diff = rangeend - rangebegin + 1;
Timestamp rand = new Timestamp(rangebegin + (long)(Math.random() * diff));



回答3:


Based on the fact that any date can be represented by a long number, take a look on this method of the Date class, http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#Date(long), you can define a maximum Date1, let's say today, and randomize the number of minutes to add.

In other words :

  • step 1 - randomize a long number or set a number for the Date1
  • step 2 - randomize the minutes to add, multiply random by 58 minutes( 58 x 60 x 1000 ) and add to Date1, plus the 2 minutes (2x 60 x 1000)



回答4:


try

    Random r = new Random();
    long t1 = System.currentTimeMillis() + r.nextInt();
    long t2 = t1 + 2 * 60 * 1000 + r.nextInt(60 * 1000) + 1;
    DateTime d1 = new DateTime(t1);
    DateTime d2 = new DateTime(t2);



回答5:


you can generate a random number using Math.random(); You can use this value.



来源:https://stackoverflow.com/questions/14771845/generating-random-date-time-in-java-joda-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!