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 can generated a random timestamp by generating a random
long
in the appropriate range and then treating it as a millisecond-precision timestamp; e.g.new Date(long)
.To determine the range, create a Date or Calendar (or similar) object that represents the start date and end date of the range, and call the
long getTime()
or equivalent to get the millisecond time values. Then generate a randomlong
in that range.IMO, the best date time library in java is JodaTime.
If you want a random TimeStam in 2012 for example you should begin with creating the 01/01/2012 date and then add a random number of time. In the end create a TimeStamp object with the long constructor :
Another way
Look this method:
For your example long value to pass into Date should be between 1325397600 and 1293861599 for year 2012.Try using this site to check! To generate random date you can do something like this:
Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.
Example: