I want to generate a random timestamp and add a random increment to it to generate a second timestamp. is that possible?
If i pass random long values to create a timestamp and i want to randomly generate that long value, what would be the constraints to generate this value to give a timestamp in 2012 for example?
解决方案
You need to scale the random number to be in the range of a specific year, and add the year's beginning as the offset. The number of milliseconds in a year changes from one year to another (leap years have an extra day, certain years have leap minutes, and so on), so you can determine the range before scaling as follows:
long offset = Timestamp.valueOf("2012-01-01 00:00:00").getTime();
long end = Timestamp.valueOf("2013-01-01 00:00:00").getTime();
long diff = end - offset + 1;
Timestamp rand = new Timestamp(offset + (long)(Math.random() * diff));