get Random Date - Java java.util

Java examples for java.util:Date Compare

Description

get Random Date

Demo Code


//package com.java2s;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static Date getRandomDate() {
        //   month
        int month = getRandomInt(1, 12);

        //   day/*ww w. j  av  a  2 s  .  c  om*/
        int day = getRandomInt(1, 28);

        //   year
        int year = getRandomInt(1970, 2009);

        String dateString = year + "-" + month + "-" + day;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sdf.parse(dateString);
        } catch (ParseException ex) {
            return new Date();
        }
    }

    public static int getRandomInt() {
        return getRandomInt(1, Integer.MAX_VALUE);
    }

    public static int getRandomInt(int min, int max) {
        return min + (int) ((Math.random() * (max - min)));
    }
}

Related Tutorials