Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Random Date time in java (joda time)

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.

like image 269
chettyharish Avatar asked Feb 08 '13 11:02

chettyharish


2 Answers

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));
like image 111
TheWhiteRabbit Avatar answered Oct 17 '22 18:10

TheWhiteRabbit


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.

like image 35
bowmore Avatar answered Oct 17 '22 16:10

bowmore