how to generate a random timestamp in java?

2019-01-17 22:01发布

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?

10条回答
祖国的老花朵
2楼-- · 2019-01-17 22:28

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);
查看更多
Luminary・发光体
3楼-- · 2019-01-17 22:29

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);
查看更多
干净又极端
4楼-- · 2019-01-17 22:31

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));
查看更多
爷的心禁止访问
5楼-- · 2019-01-17 22:31
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) ;
查看更多
登录 后发表回答