Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate a random timestamp in java?

Tags:

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?

like image 735
Sami Avatar asked Jun 13 '12 13:06

Sami


People also ask

How do you do a random timestamp?

To generate a random timestamp between the two Unix times start and end , it generates a random integer via the formula Math. floor(Math. random()*(end-start+1))+start . In total, it generates count timestamps.

How do you generate random time in Java?

sql. Time; final Random random = new Random(); final int millisInDay = 24*60*60*1000; Time time = new Time((long)random. nextInt(millisInDay));

How do I generate random Localdatetime?

A simple way is to convert the minimum and maximum date to their corresponding epoch day, generate a random integer between those two values and finally convert it back to a LocalDate . The epoch day is obtained with toEpochDay() which is the count of days since 1970-01-01 (ISO).

Can we generate random string in Java?

java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


1 Answers

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)); 
like image 153
Sergey Kalinichenko Avatar answered Sep 23 '22 07:09

Sergey Kalinichenko