0

Time 1 : 10:30 06/05/2018

Time 2 : 19:45 06/05 2018

I want to pick a random time between these two time. The result may be (13:15 06/05/2018).

I look into Calendar but seem it does not support a method like range(time1, time2)

What is the solution for this case ? Thanks.

CauCuKien
  • 1,027
  • 2
  • 15
  • 26
  • 1
    https://stackoverflow.com/questions/11016336/how-to-generate-a-random-timestamp-in-java – AskNilesh May 06 '18 at 06:22
  • https://stackoverflow.com/questions/41802925/how-to-get-any-random-time-between-now-and-last-three-hours-using-java – AskNilesh May 06 '18 at 06:23
  • https://stackoverflow.com/questions/41802925/how-to-get-any-random-time-between-now-and-last-three-hours-using-java – AskNilesh May 06 '18 at 06:24

2 Answers2

3

I would use something like this.

public static Calendar getRandomTime(Calendar begin, Calendar end){
        Random rnd = new Random();
        long min = begin.getTimeInMillis();
        long max = end.getTimeInMillis();
        long randomNum = min + rnd.nextLong()%(max - min + 1);
        Calendar res = Calendar.getInstance();
        res.setTimeInMillis(randomNum);
        return res;
    }

if you have API 21+, use ThreadLocalRandom

public static Calendar getRandomTime(Calendar begin, Calendar end){
    long randomNum = ThreadLocalRandom.current().nextLong(begin.getTimeInMillis(), end.getTimeInMillis() + 1);
    Calendar res = Calendar.getInstance();
    res.setTimeInMillis(randomNum);
    return res;
}
Irshad P I
  • 2,394
  • 2
  • 14
  • 23
2

you should convert your times objects to long first as follows (I suppose that you have two Calendar objects already)

long time1InLong = time1.getTimeInMillis();
long time2InLong = time2.getTimeInMillis();

Then you can use following code to generate random number

Random r = new Random();
long randomTime = r.nextLong(time2InLong - time1InLong) + time1InLong;

Then you can convert this randomTime back to Calendar as follows

// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");

// Create a calendar object that will convert the date and time value in milliseconds to date. 
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(randomTime);
Fahed Yasin
  • 400
  • 2
  • 9