Generate random date

This example shows how to generate a random date using java, java8 date time api and joda time. In the set up, the beginTime is set to start of the year and endTime to the last day of the year. A method getRandomTimeBetweenTwoDates generates random number that represents a time between two dates. With each apporach, it will call this method creating a new random date.

Setup

private long beginTime;
private long endTime;

@Before
public void setUp () {
    beginTime = Timestamp.valueOf("2013-01-01 00:00:00").getTime();
    endTime = Timestamp.valueOf("2013-12-31 00:58:00").getTime();
}

/**
 * Method should generate random number that represents 
 * a time between two dates.
 * 
 * @return
 */
private long getRandomTimeBetweenTwoDates () {
    long diff = endTime - beginTime + 1;
    return beginTime + (long) (Math.random() * diff);
}

Straight up Java

@Test
public void generate_random_date_java() {

    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd hh:mm:ss");

    for (int x = 0; x < 7; x++) {
        Date randomDate = new Date(getRandomTimeBetweenTwoDates());

        logger.info(dateFormat.format(randomDate));

        assertThat(
                randomDate.getTime(),
                allOf(lessThanOrEqualTo(endTime),
                        greaterThanOrEqualTo(beginTime)));
    }
}

Output

2013-02-01 03:13:49
2013-12-10 03:23:25
2013-01-20 03:48:31
2013-06-21 12:03:35
2013-08-25 12:16:13
2013-05-24 11:52:25
2013-06-01 12:06:48

Java 8 Date and Time API

@Test
public void generate_random_date_java8() {

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
    
    for (int x = 0; x < 7; x++) {
        
        Instant instant = Instant.ofEpochSecond(getRandomTimeBetweenTwoDates());
        LocalDateTime randomDate = LocalDateTime.ofInstant(instant, ZoneId.of("UTC-06:00")); 

        logger.info(randomDate.format(format));

        assertThat(
                randomDate.atZone(ZoneId.of("UTC-06:00")).toEpochSecond(),
                allOf(lessThanOrEqualTo(endTime),
                        greaterThanOrEqualTo(beginTime)));
    }
}

Output

+45480-01-23 05:25:24
+44972-05-30 12:56:24
+45798-10-18 08:32:19
+45130-12-07 12:57:17
+45636-11-04 01:04:39
+45126-10-15 08:21:35
+45959-03-30 08:06:20

Joda Time

@Test
public void generate_random_date_joda () {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    for (int x=0; x < 7; x ++) {
        
        DateTime randomDate = new DateTime(getRandomTimeBetweenTwoDates());
        
        logger.info(dateFormat.format(randomDate.getMillis()));
        
        assertThat(
                randomDate.getMillis(),
                allOf(lessThanOrEqualTo(endTime),
                        greaterThanOrEqualTo(beginTime)));
    }
}

Output

2013-09-29 11:43:01
2013-05-17 05:53:12
2013-01-21 02:20:09
2013-08-11 12:57:38
2013-09-25 06:29:28
2013-07-29 01:20:02
2013-08-04 10:13:44