24

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?

Sami
  • 7,797
  • 18
  • 45
  • 69

11 Answers11

57

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));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Clearly the best answer for this question. This may seem like a dumb question, however why add 1 to the subtraction of `end` and `offset`? – Priidu Neemre Feb 04 '13 at 17:13
  • 5
    @Priidu You need to add `1` to make sure that you get the full range for the resultant random value. Consider this example: let's say you get an offset of `11`, and `end` of `15`. If you remove `+1`, the `diff` would be `4`. Therefore, the `(long)(Math.random() * diff)` would be from zero to `3`, because `Math.random()` is strictly less than `1.0`. This means that you'd never get the result of `15`, which is undesirable. – Sergey Kalinichenko Feb 04 '13 at 17:46
6

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);
Aleksandr Kravets
  • 5,750
  • 7
  • 53
  • 72
  • He said "for example" he doesn't need the ranges for 2012, he needs a generic way to do it for any two dates. – Pablo Jun 13 '12 at 14:04
  • @Pablo: well i also gave him convenient link to determine any other unix-time values he wants. – Aleksandr Kravets Jun 13 '12 at 14:06
  • I found I had to multiply the epoch date in Aleksandr's answer by 1000, as java.util.Date(long) expects the epoch number in *milliseconds*, not seconds. So I used (long) (1293861599000l + r.nextDouble()*60*60*24*365*1000); – James Allen Dec 16 '15 at 15:05
2

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()));
}
Ganesh Joshi
  • 155
  • 1
  • 7
uris
  • 5,993
  • 3
  • 25
  • 24
1

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

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())
jocelyn
  • 788
  • 6
  • 12
1

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);
Keppil
  • 45,603
  • 8
  • 97
  • 119
0

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);
vbezhenar
  • 11,148
  • 9
  • 49
  • 63
0

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));
}
Alberto Cerqueira
  • 1,339
  • 14
  • 18
0

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;
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
vsingh
  • 6,365
  • 3
  • 53
  • 57
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) ;
donald
  • 478
  • 8
  • 19
0

I am actually coding in scala, but it may be useful anyway

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)}
Galuoises
  • 2,630
  • 24
  • 30