如何在java中生成随机时间戳?

时间:2012-06-13 13:51:45

标签: java random timestamp

我想生成一个随机时间戳并为其添加一个随机增量以生成第二个时间戳。那可能吗?

如果我传递随机长值来创建时间戳,并且我想随机生成那个长值,那么生成此值以在2012年给出时间戳的约束是什么?

11 个答案:

答案 0 :(得分:44)

您需要将随机数缩放到特定年份的范围内,并将年份的开头添加为偏移量。一年中的毫秒数从一年变为另一年(闰年有一天,某些年有闰分,依此类推),因此您可以在缩放前确定范围,如下所示:

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

答案 1 :(得分:6)

对于您的示例,传入日期的长值应介于2012年的 1325397600 1293861599 之间。请尝试使用this site进行检查!要生成随机日期,您可以执行以下操作:

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

答案 2 :(得分:2)

使用ApacheCommonUtils在给定范围内生成随机长度,然后在该长度内创建Date。

示例:

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

答案 3 :(得分:1)

您可以通过在适当的范围内生成随机long然后将其视为毫秒精度时间戳来生成随机时间戳;例如new Date(long)

要确定范围,请创建表示范围的开始日期和结束日期的日期或日历(或类似)对象,并调用long getTime()或等效项以获取毫秒时间值。然后在该范围内生成随机long

答案 4 :(得分:1)

IMO,java中最好的日期时间库是JodaTime。

如果您想在2012年使用随机TimeStam,则应首先创建01/01/2012日期,然后添加随机时间。最后使用long构造函数创建一个TimeStamp对象:

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

答案 5 :(得分:1)

首先找出2012年的开始:

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

在这一年中获得随机毫秒:

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

答案 6 :(得分:0)

以下代码生成2012年的随机时间戳。

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

答案 7 :(得分:0)

看看这个方法:

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

答案 8 :(得分:0)

另一种方式

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

答案 9 :(得分:0)

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

答案 10 :(得分:0)

我实际上是用 Scala 编码的,但它可能还是有用的

import scala.util.Random
import java.sql.Timestamp

def generateRandomTimestamp(dateStringMin: String = "2000-01-01 00:00:00", dateStringMax: String = "2021-12-31 00:00:00"): java.sql.Timestamp = {
    val date1 = Timestamp.valueOf(dateStringMin).getTime()
    val date2 = Timestamp.valueOf(dateStringMax).getTime()
    val diff = date2 - date1
    new Timestamp(date1 + (Random.nextFloat() * diff).toLong)}