1

How I can generate random unix timestamp in specific times. For example get random unix time mean between today and tomorrow.

user1021984
  • 621
  • 3
  • 9
  • 25
  • maybe you can find something useful here: http://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range – rosco Jun 08 '12 at 15:01

3 Answers3

3
long randomEpoch = epoch1 + Math.abs(new Random().nextLong()) % (epoch2-epoch1);

where epoch1 and epoch2 are the two times.

Hari Menon
  • 33,649
  • 14
  • 85
  • 108
  • very good! I did: new Date(Math.abs(new Random().nextLong()) % new Date().getTime()) to get a random date between 1/1/1970 to today – ademar111190 Jan 02 '13 at 06:28
1

Get the needed range by generating two timestamps. Subtract the difference (absolute value). Get a random number between 0 and 1. Multiply the difference by the random number. Add the result to the earlier timestmap.

jn1kk
  • 5,012
  • 2
  • 45
  • 72
0

This code specifically gets a random time between today and tomorrow.

public Date randTime(){
    Date now = new Date();
    Date today = new Date(now.getFullYear(), now.getMonth(), now.getDay(), 0, 0, 0, 0);
    return new Date(today.getTime() + (long)(Math.random() * 86400000));
}
Hans Z
  • 4,664
  • 2
  • 27
  • 50