Java 生成随机出生日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3985392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:56:47  来源:igfitidea点击:

Generate random date of birth

javarandom

提问by user475529

I'm trying to generate a random date of birth for people in my database using a Java program. How would I do this?

我正在尝试使用 Java 程序为我的数据库中的人生成随机出生日期。我该怎么做?

采纳答案by Saul

import java.util.GregorianCalendar;

public class RandomDateOfBirth {

    public static void main(String[] args) {

        GregorianCalendar gc = new GregorianCalendar();

        int year = randBetween(1900, 2010);

        gc.set(gc.YEAR, year);

        int dayOfYear = randBetween(1, gc.getActualMaximum(gc.DAY_OF_YEAR));

        gc.set(gc.DAY_OF_YEAR, dayOfYear);

        System.out.println(gc.get(gc.YEAR) + "-" + (gc.get(gc.MONTH) + 1) + "-" + gc.get(gc.DAY_OF_MONTH));

    }

    public static int randBetween(int start, int end) {
        return start + (int)Math.round(Math.random() * (end - start));
    }
}

回答by T.J. Crowder

java.util.Datehas a constructorthat accepts milliseconds since The Epoch, and java.util.Randomhas a methodthat can give you a random number of milliseconds. You'll want to set a range for the random value depending on the range of DOBs that you want, but those should do it.

java.util.Date有一个构造函数,它接受自 The Epoch 以来的毫秒数,并且java.util.Random一个方法可以为您提供随机数的毫秒数。您需要根据您想要的 DOB 范围设置随机值的范围,但这些应该这样做。

Veryroughly:

非常粗略:

Random  rnd;
Date    dt;
long    ms;

// Get a new random instance, seeded from the clock
rnd = new Random();

// Get an Epoch value roughly between 1940 and 2010
// -946771200000L = January 1, 1940
// Add up to 70 years to it (using modulus on the next long)
ms = -946771200000L + (Math.abs(rnd.nextLong()) % (70L * 365 * 24 * 60 * 60 * 1000));

// Construct a date
dt = new Date(ms);

回答by Romain Linsolas

You need to define a random date, right?

您需要定义一个随机日期,对吗?

A simple way of doing that is to generate a new Dateobject, using a long(time in milliseconds since 1st January, 1970) and substract a random long:

一个简单的方法是生成一个新Date对象,使用long自 1970 年 1 月 1 日以来的毫秒数)并减去随机数long

new Date(Math.abs(System.currentTimeMillis() - RandomUtils.nextLong()));

(RandomUtilsis taken from Apache Commons Lang).

RandomUtils取自 Apache Commons Lang)。

Of course, this is far to be a real random date (for example you will not get date before 1970), but I think it will be enough for your needs.

当然,这远不是一个真正的随机日期(例如,您不会在 1970 年之前获得日期),但我认为这足以满足您的需求。

Otherwise, you can create your own date by using Calendarclass:

否则,您可以使用Calendar类创建自己的日期:

int year = // generate a year between 1900 and 2010;
int dayOfYear = // generate a number between 1 and 365 (or 366 if you need to handle leap year);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, randomYear);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
Date randomDoB = calendar.getTime();

回答by BALAJI POTHULA

Generating random Date of Births:

生成随机出生日期:

import java.util.Calendar;

public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 100; i++) {
        System.out.println(randomDOB());
    }
  }

  public static String randomDOB() {

    int yyyy = random(1900, 2013);
    int mm = random(1, 12);
    int dd = 0; // will set it later depending on year and month

    switch(mm) {
      case 2:
        if (isLeapYear(yyyy)) {
          dd = random(1, 29);
        } else {
          dd = random(1, 28);
        }
        break;

      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        dd = random(1, 31);
        break;

      default:
        dd = random(1, 30);
      break;
    }

    String year = Integer.toString(yyyy);
    String month = Integer.toString(mm);
    String day = Integer.toString(dd);

    if (mm < 10) {
        month = "0" + mm;
    }

    if (dd < 10) {
        day = "0" + dd;
    }

    return day + '/' + month + '/' + year;
  }

  public static int random(int lowerBound, int upperBound) {
    return (lowerBound + (int) Math.round(Math.random()
            * (upperBound - lowerBound)));
  }

  public static boolean isLeapYear(int year) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    int noOfDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);

    if (noOfDays > 365) {
        return true;
    }

    return false;
  }
}

回答by B.Mr.W.

I am studying Scala and ended up Googling Java solutions for choosing a random date between range. I found thispost super helpful and this is my final solution. Hope it can help future Scala and Java programmers.

我正在学习 Scala 并最终使用谷歌搜索 Java 解决方案来选择范围之间的随机日期。我发现这篇文章非常有帮助,这是我的最终解决方案。希望它可以帮助未来的 Scala 和 Java 程序员。

import java.sql.Timestamp

def date_rand(ts_start_str:String = "2012-01-01 00:00:00", ts_end_str:String = "2015-01-01 00:00:00"): String = {
    val ts_start = Timestamp.valueOf(ts_start_str).getTime()
    val ts_end = Timestamp.valueOf(ts_end_str).getTime()
    val diff = ts_end - ts_start
    println(diff)
    val ts_rand = new Timestamp(ts_start + (Random.nextFloat() * diff).toLong)
    return ts_rand.toString
}                                         //> date_rand: (ts_start_str: String, ts_end_str: String)String

println(date_rand())                      //> 94694400000
                                              //| 2012-10-28 18:21:13.216

println(date_rand("2001-01-01 00:00:00", "2001-01-01 00:00:00"))
                                              //> 0
                                              //| 2001-01-01 00:00:00.0
println(date_rand("2001-01-01 00:00:00", "2010-01-01 00:00:00"))
                                              //> 283996800000
                                              //| 2008-02-16 23:15:48.864                    //> 2013-12-21 08:32:16.384

回答by Jens Hoffmann

Snippet for a Java 8 based solution:

基于 Java 8 的解决方案的片段:

Random random = new Random();
int minDay = (int) LocalDate.of(1900, 1, 1).toEpochDay();
int maxDay = (int) LocalDate.of(2015, 1, 1).toEpochDay();
long randomDay = minDay + random.nextInt(maxDay - minDay);

LocalDate randomBirthDate = LocalDate.ofEpochDay(randomDay);

System.out.println(randomBirthDate);

Note: This generates a random date between 1Jan1900 (inclusive) and 1Jan2015 (exclusive).

注意:这会生成一个介于 1Jan1900(含)和 1Jan2015(不含)之间的随机日期。

Note: It is based on epoch days, i.e. days relative to 1Jan1970 (EPOCH) - positive meaning after EPOCH, negative meaning before EPOCH

注意:它基于纪元天数,即相对于 1Jan1970 ( EPOCH) 的天数- EPOCH之后的正值,EPOCH 之前的负值



You can also create a small utility class:

您还可以创建一个小的实用程序类:

public class RandomDate {
    private final LocalDate minDate;
    private final LocalDate maxDate;
    private final Random random;

    public RandomDate(LocalDate minDate, LocalDate maxDate) {
        this.minDate = minDate;
        this.maxDate = maxDate;
        this.random = new Random();
    }

    public LocalDate nextDate() {
        int minDay = (int) minDate.toEpochDay();
        int maxDay = (int) maxDate.toEpochDay();
        long randomDay = minDay + random.nextInt(maxDay - minDay);
        return LocalDate.ofEpochDay(randomDay);
    }

    @Override
    public String toString() {
        return "RandomDate{" +
                "maxDate=" + maxDate +
                ", minDate=" + minDate +
                '}';
    }
}

and use it like this:

并像这样使用它:

RandomDate rd = new RandomDate(LocalDate.of(1900, 1, 1), LocalDate.of(2010, 1, 1));
System.out.println(rd.nextDate());
System.out.println(rd.nextDate()); // birthdays ad infinitum

回答by Ronak Poriya

You can checkout randomizerfor random data generation.This library helps to create random data from given Model class.Checkout below example code.

您可以检查随机数据生成的随机数。这个库有助于从给定的模型类创建随机数据。在下面的示例代码中检查。

public class Person {

    @DateValue( from = "01 Jan 1990",to = "31 Dec 2002" , customFormat = "dd MMM yyyy")
    String dateOfBirth;

}

//Generate random 100 Person(Model Class) object 
Generator<Person> generator = new Generator<>(Person.class);  
List<Person> persons = generator.generate(100);                          

As there are many built in data generator is accessible using annotation,You also can build custom data generator.I suggest you to go through documentation provided on library page.

由于有许多内置数据生成器可以使用注释访问,您也可以构建自定义数据生成器。我建议您阅读库页面上提供的文档。

回答by Alberto Cerqueira

Look this method:

看看这个方法:

public static Date 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;
    Timestamp timestamp = new Timestamp(offset + (long) (Math.random() * diff));
    return new Date(timestamp.getTime());
}

回答by Andrei Ciobanu

If you don't mind adding a new library to your code you can use MockNeat(disclaimer: I am one of the authors).

如果你不介意在你的代码中添加一个新的库,你可以使用MockNeat(免责声明:我是作者之一)。

MockNeat mock = MockNeat.threadLocal();

// Generates a random date between [1970-1-1, NOW)
LocalDate localDate = mock.localDates().val();
System.out.println(localDate);

// Generates a random date in the past
// but beore 1987-1-30
LocalDate min = LocalDate.of(1987, 1, 30);
LocalDate past = mock.localDates().past(min).val();
System.out.println(past);

LocalDate max = LocalDate.of(2020, 1, 1);
LocalDate future = mock.localDates().future(max).val();
System.out.println(future);

// Generates a random date between 1989-1-1 and 1993-1-1
LocalDate start = LocalDate.of(1989, 1, 1);
LocalDate stop = LocalDate.of(1993, 1, 1);
LocalDate between = mock.localDates().between(start, stop).val();
System.out.println(between);

回答by Witold Kaczurba

For Java8 -> Assumming the data of birth must be before current day:

对于 Java8 -> 假设出生数据必须在当天之前:

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Random;

public class RandomDate {

    public static LocalDate randomBirthday() {
        return LocalDate.now().minus(Period.ofDays((new Random().nextInt(365 * 70))));
    }

    public static void main(String[] args) {
        System.out.println("randomDate: " + randomBirthday());
    }
}