Random Date Generator dengan Java

Iseng-iseng bikin class sederhana untuk menghasilkan suatu tanggal random yang terletak antara tanggalSebelum (Date) dan tanggalSesudah (Date). Rencananya ini mo gw pakek bwt testing aplikasi. Sorry klo classnya rada berantakan, bikinnya juga buru-buru, sembari nunggu adzan Maghrib.

package com.edw.random;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 
 * @author edwin
 */
public class RandomDateGenerator extends Thread {

	private Date sebelum;
	private Date sesudah;
	private int repetition;

	public Date getSebelum() {
		return sebelum;
	}

	public void setSebelum(Date sebelum) {
		this.sebelum = sebelum;
	}

	public Date getSesudah() {
		return sesudah;
	}

	public void setSesudah(Date sesudah) {
		this.sesudah = sesudah;
	}

	public int getRepetition() {
		return repetition;
	}

	public void setRepetition(int repetition) {
		this.repetition = repetition;
	}

	public RandomDateGenerator() {
	}

	@Override
	public void run() {
		try {
			for (int i = 0; i < repetition; i++) {
				Thread.sleep(1000);
				System.out.println(getRandomDateBetween(sebelum, sesudah));
			}
		} catch (InterruptedException interruptedException) {
			interruptedException.printStackTrace();
		}
	}

	private synchronized Date getRandomDateBetween(Date from, Date to) {
		Calendar cal = Calendar.getInstance();

		cal.setTime(from);
		BigDecimal decFrom = new BigDecimal(cal.getTimeInMillis());

		cal.setTime(to);
		BigDecimal decTo = new BigDecimal(cal.getTimeInMillis());

		BigDecimal selisih = decTo.subtract(decFrom);
		BigDecimal factor = selisih.multiply(new BigDecimal(Math.random()));

		return new Date((factor.add(decFrom)).longValue());
	}

	public static void main(String[] args) throws Exception {
		RandomDateGenerator rdg = new RandomDateGenerator();
		rdg.setSebelum(new SimpleDateFormat("dd MM yyyy").parse("17 08 1978"));
		rdg.setSesudah(new SimpleDateFormat("dd MM yyyy").parse("17 08 1990"));
		rdg.setRepetition(10);
		rdg.start();
	}
}

may the SOURCE be with you.

Wassalam.

Leave a Comment

Your email address will not be published.