Generate random date of birth
我试图用Java程序在数据库中生成一个随机的出生日期。我该怎么做?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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)); } } |
。
非常粗略地说:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); |
基于Java 8的解决方案的片段:
1 2 3 4 5 6 7 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); |
。
注:这将生成1900年1月1日(含)至2015年1月1日(不含)之间的随机日期。
注:以纪元日为基础,即相对于1970年1月1日(历元)的日数——历元后的正意义,历元前的负意义。
还可以创建一个小型实用程序类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 + '}'; } } |
像这样使用:
1 2 3 |
。
你需要定义一个随机日期,对吗?
一种简单的方法是使用
号
(randomutils取自apache commons lang)。
当然,这远不是一个真正的随机日期(例如,你在1970年之前不会得到日期),但我认为这足以满足你的需要。
否则,您可以使用
1 2 3 4 5 6 | 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(); |
对于java8->assumming,出生数据必须在当天之前:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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()); } } |
号
如果您不介意在代码中添加新的库,可以使用mockneat(免责声明:我是作者之一)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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); |
号
看这个方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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()); } |
。
您可以签出随机数发生器以生成随机数据。此库有助于从给定的模型类创建随机数据。签出以下示例代码。
1 2 3 4 5 6 7 8 9 10 | 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); |
因为有许多内置的数据生成器可以使用注释访问,所以您也可以构建自定义的数据生成器。我建议您阅读库页面上提供的文档。
生成随机出生日期:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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; } } |
如果您不介意第三方库,则UITLS库有一个随机数据池,它可以从Java 8的日期和时间API生成随机JavaUTL日期和所有日期、时间、瞬间和持续时间。
1 2 3 4 | LocalDate birthDate = RandomDateUtils.randomPastLocalDate(); LocalDate today = LocalDate.now(); LocalDate under18YearsOld = RandomDateUtils.randomLocalDate(today.minus(18, YEARS), today); LocalDate over18YearsOld = RandomDateUtils.randomLocalDateBefore(today.minus(18, YEARS)); |
号
它位于Maven中央存储库中:
1 2 3 4 5 | <dependency> <groupId>com.github.rkumsher</groupId> utils</artifactId> <version>1.3</version> </dependency> |
号
我认为这将起到关键作用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static void main(String[] args) { Date now = new Date(); long sixMonthsAgo = (now.getTime() - 15552000000l); long today = now.getTime(); for(int i=0; i<10; i++) { long ms = ThreadLocalRandom.current().nextLong(sixMonthsAgo, today); Date date = new Date(ms); System.out.println(date.toString()); } } |
号
我是studying Scala,结束Google Java解决方案来选择范围之间的随机日期。我发现这篇文章非常有用,这是我的最终解决方案。希望能对未来的斯卡拉和Java程序员有所帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 |
。