how to generate a random timestamp in java?

2019-01-17 21:47发布

问题:

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?

回答1:

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));


回答2:

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:

Random r =new Random();
long unixtime=(long) (1293861599+r.nextDouble()*60*60*24*365);
Date d = new Date(unixtime);


回答3:

Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.

Example:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public Date nextDate(Date min, Date max) {

      RandomData randomData = new RandomDataImpl();
      return new Date(randomData.nextLong(min.getTime(), max.getTime()));
}


回答4:

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 random long in that range.



回答5:

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 :

org.joda.time.DateTime tempDateTime = org.joda.time.DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime("2012-01-01").plusMillis(my_random_value);
return new Timestamp(tempDateTime .getMillis())


回答6:

Start by finding out the start of the year 2012:

    long start2012 = new SimpleDateFormat("yyyy").parse("2012").getTime();

Get a random millisecond during the year:

    final long millisInYear2012 = 1000 * 60 * 60 * 24 * 365 + 1000; // Have to account for the leap second!
    long millis = Math.round(millisInYear2012 * Math.random());
    Timestamp timeStamp = new Timestamp(start2012 + millis);


回答7:

Following code generates random timestamp for 2012 year.

    DateFormat dateFormat = new SimpleDateFormat("yyyy");
    Date dateFrom = dateFormat.parse("2012");
    long timestampFrom = dateFrom.getTime();
    Date dateTo = dateFormat.parse("2013");
    long timestampTo = dateTo.getTime();
    Random random = new Random();
    long timeRange = timestampTo - timestampFrom;
    long randomTimestamp = timestampFrom + (long) (random.nextDouble() * timeRange);


回答8:

Look this method:

public static Timestamp dateRandom(int initialYear, int lastYear) {
    if (initialYear > lastYear) {
        int year = lastYear;
        lastYear = initialYear;
        initialYear = year;
    }

    Calendar cInitialYear = Calendar.getInstance();
    cInitialYear.set(Calendar.YEAR, 2015);
    long offset = cInitialYear.getTimeInMillis();

    Calendar cLastYear = Calendar.getInstance();
    cLastYear.set(Calendar.YEAR, 2016);
    long end = cLastYear.getTimeInMillis();

    long diff = end - offset + 1;
    return new Timestamp(offset + (long) (Math.random() * diff));
}


回答9:

Another way

public static Timestamp getRandomTime(){

  Random r = new Random();
  int Low = 100;
  int High = 1500;
  int Result = r.nextInt(High-Low) + Low;
  int ResultSec = r.nextInt(High-Low) + Low;

  Calendar calendar = Calendar.getInstance();
  calendar.add(Calendar.MINUTE, - Result);
  calendar.add(Calendar.SECOND, - ResultSec);

  java.sql.Timestamp ts = new java.sql.Timestamp(calendar.getTimeInMillis());
  return ts;
}


回答10:

import org.joda.time.*;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

    DateTime d1 =DateTime.now().withZone(DateTimeZone.UTC);
        DateTime d0 = d1.minusSeconds(20);
        DateTime d2 = d1.plusSeconds(20);



        Random r = new Random();
        long t1 = d0.getMillis();
        long t2 = d2.getMillis();
        //DateTime d1 = new DateTime(t1);
        //DateTime d2 = new DateTime(t2);
        Random random = new Random();
        long rand = t1 + (long) (random.nextDouble() * (t2-t1));

        DateTime randDatetime = new DateTime(rand);

        String datestr= randDatetime.toString("MM/dd/YYYY hh:mm:ss") ;
        System.out.println(datestr) ;