smushi
smushi

Reputation: 719

Generate Java Dates but constant date and different times

I am trying to generate random dates as Java Dates but the date remains the same. I want the time to be random only, not the date.

E.g. test case 1: 1/1/2013 9:08:52

test case 2: 1/1/2013 15:01: 42 etc.

Any ideas?

hey guys i found something that works. Thanks for the help!

import java.util.Random;
import java.sql.Time;

public class Clock2 {
public static void main(String[] args) {

    for (int i=0; i< 100; i++){ 
        final Random random = new Random();
        final int millisInDay = 24*60*60*1000;
        Time time = new Time((long)random.nextInt(millisInDay));
        System.out.println(time);
    }

}

Upvotes: 1

Views: 330

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

try

    Random r = new Random();
    GregorianCalendar c = new GregorianCalendar(r.nextInt(100) + 2000, r.nextInt(11), r.nextInt(31));
    long t0 = c.getTimeInMillis();
    for(int i = 0; i < 10; i++) {
        Date d = new Date(t0 + r.nextInt(24 * 3600 * 1000));
        System.out.println(d);
    }

Upvotes: 0

chopchop
chopchop

Reputation: 1933

Use this to find out the start and end Unix timestamps for the date you desire: http://www.epochconverter.com/

Generate a random long between those two values. Eventually format the long by using a SimpleDateFormat http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Upvotes: 1

Related Questions