Generate random date of birth
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));
}
}
Java - Generate Random DOB
Apart from the desired formatting of you date I see some other problems with your code that I think you would want to address:
- Assuming you want a usual month number, 01 for January through 12 for December, your handling of the month number is not correct.
get(Calendar.MONTH)
gives you a 0-based month: 0 for January through 11 for December. Therefore, your code not only will never give you 12 as month and 1 all too often. It will also give you non-existing dates. I have seen 1905-2-31 and 1929-4-31 (because you get 2 for March, which we interpret as February, etc.). - Possibly unimportant, your distribution gives each day in a leap year slightly smaller probablity than other days.
If you can, I suggest you use LocalDate
. The class was introduced in Java 8:
private static String randomDataOfBirth(int yearStartInclusive, int yearEndExclusive) {
LocalDate start = LocalDate.ofYearDay(yearStartInclusive, 1);
LocalDate end = LocalDate.ofYearDay(yearEndExclusive, 1);
long longDays = ChronoUnit.DAYS.between(start, end);
int days = (int) longDays;
if (days != longDays) {
throw new IllegalStateException("int overflow; too many years");
}
int day = randBetween(0, days);
LocalDate dateOfBirth = start.plusDays(day);
return dateOfBirth.toString();
}
This gives you evenly distributed, correct dates formatted with 2 digits for month and day-of-month, e.g., 1926-07-05
.
If you want to avoid the overflow check, you may of course rewrite your randBetween()
to handle long
s.
If you cannot use Java 8, you can do something similar with GregorianCalendar
and SimpleDateFormat
. Counting the exact number of days from lower to upper bound is complicated, though, so you will probably want to stick to your way of picking the date. SimpleDateFormat
can still give you correct dates formatted with two digits for month and day. Edit: In your class, declare:
static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Now just substitute your if
-else
statement with this:
String date = formatter.format(gc.getTime());
If your randomDataOfBirth()
may be accessed from more than one thread, this won’t work since SimpleDateFormat
is not thread-safe. If so, each thread should have its own SimpleDateFormat
instance.
How to generate random data of birth dates using google spreadsheets for a specific years?
You could try (as I demonstrated in your sheet):
=ARRAY_CONSTRAIN(SORT(SEQUENCE(DATE(1992,12,31)-DATE(1900,1,1),1,DATE(1900,1,1)),RANDARRAY(DATE(1992,12,31)-DATE(1900,1,1)),1),COUNTA(A2:A),1)
SEQUENCE(DATE(1992,12,31)-DATE(1900,1,1),1,DATE(1900,1,1))
- Is used to create an array of valid numeric representations of true dates between 1-1-1900 and 31-12-1992.SORT(<TheAbove>,RANDARRAY(DATE(1992,12,31)-DATE(1900,1,1)),1)
- Is used to sort the array we just created randomly.ARRAY_CONSTRAIN(<TheAbove>, COUNTA(A2:A),1)
- Is used to only return as many random birth-dates we need according to other data.
Note that this is volatile and will recalculate upon sheet-changes and such. Also note that this is just "slicing" a given array and may fall short when you try to use it on a dataset larger than the given array.
Generate a random date between two other dates
Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]
) with that difference, and add again to the earlier one. Convert the timestamp back to date string and you have a random time in that range.
Python example (output is almost in the format you specified, other than 0
padding - blame the American time format conventions):
import random
import time
def str_time_prop(start, end, time_format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formatted in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
stime = time.mktime(time.strptime(start, time_format))
etime = time.mktime(time.strptime(end, time_format))
ptime = stime + prop * (etime - stime)
return time.strftime(time_format, time.localtime(ptime))
def random_date(start, end, prop):
return str_time_prop(start, end, '%m/%d/%Y %I:%M %p', prop)
print(random_date("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", random.random()))
Postman Pre-request Script: Need to generate a random DOB (18 years or older)
Thanks, @Hans for your solution. I took that and modified it a bit. Its not the Smartest way, but i am sure it does the required. By following the below steps, the YYYY of DOB returned will be always between 1990 and 1999, so that the user is always greater than 18 Years old.
//Genrate random Date of Birth in MM/DD/YY Format and the DOB always fall in between 1990 and 1999
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
var date = randomDate(new Date(2000, 0, 1), new Date());
var year_last_integer = Math.floor(Math.random() * 10);
var formattedDate = (date.getMonth()+1) + '/' + date.getDate() + '/' + '199' + year_last_integer;
pm.environment.set("dob", formattedDate);
console.log("DOB: " + formattedDate);
Creating x number of random date of births and x number of dates that are at least 18 years after corresponding date of birth?
I think this will work for you:
birthdates = []
import time
import random
def strTimeProp(start, end, format, prop):
"""Get a time at a proportion of a range of two formatted times.
start and end should be strings specifying times formated in the
given format (strftime-style), giving an interval [start, end].
prop specifies how a proportion of the interval to be taken after
start. The returned time will be in the specified format.
"""
if len(start) == 6:
start = '0' + start[0] + '0' + start[1:]
elif len(start) == 7:
start = '0' + start
try:
stime = time.mktime(time.strptime(start, format))
except:
year = start[:-4]
stime = time.mktime(time.strptime("February 28 " + year, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop, list):
list.append(strTimeProp(start, end, '%B %d %Y', prop))
for n in range(1000):
randomDate("January 1 1960", "June 1 2001", random.random(), birthdates)
later_dates = []
for date in birthdates:
month_day = date[:-4]
year = date[-4:]
randomDate(month_day + str(int(year) + 18), "June 1 2019", random.random(), later_dates)
The list later_dates
will contain a list of the dates you want.
How do I generate any random date between 01/01/2016 to 01/01/2017 using Java?
If using Java 8 I'd suggest using the new java.time
API:
LocalDate from = LocalDate.of(2016, 1, 1);
LocalDate to = LocalDate.of(2017, 1, 1);
long days = from.until(to, ChronoUnit.DAYS);
long randomDays = ThreadLocalRandom.current().nextLong(days + 1);
LocalDate randomDate = from.plusDays(randomDays);
System.out.println(randomDate.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));
Change days + 1
to days
if you do not want to randomly generate 01/01/2017 i.e. the end date is exclusive.
How to generate random date between two dates using php?
PHP has the rand() function:
$int= rand(1262055681,1262055681);
It also has mt_rand(), which is generally purported to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
generate a birthday date randomly in c
As Barmar's comment, you can't assume that jour_c
and mois_c
are one-character strings. Use
Date[0] = '\0'; // or you can initialize it as signed char Date[20] = {0};
strcat(Date, jour_c);
strcat(Date, "/");
strcat(Date, mois_c);
strcat(Date, "/");
strcat(Date, annee_c);
instead of
Date[0]=jour_c[0];
Date[1]=jour_c[1];Date[2]='/';
Date[3]=mois_c[0];Date[4]=mois_c[1];Date[5]='/';
Date[6]=annee_c[0];Date[7]=annee_c[1];Date[8]=annee_c[2];Date[9]=annee_c[3];Date[10]='\0';
Generating random date in a specific range in JAVA
Given that your question is unclear, I am expecting you are trying to generate random java.util.Date
with given range.
Please note that java.util.Date
contains date + time information.
Date
in Java is represented by milliseconds from EPOCH. Therefore the easiest way to do what you want is, given d1 and d2 is Date
, and d1 < d2 (in pseudo-code):
Date randomDate = new Date(ThreadLocalRandom.current()
.nextLong(d1.getTime(), d2.getTime()));
If it is actually a "Date" (without time) that you want to produce, which is usually represented by LocalDate
(in Java 8+, or using JODA Time).
It is as easy as, assume d1 and d2 being LocalDate
, with d1 < d2
(pseudo-code):
int days = Days.daysBetween(d1, d2).toDays();
LocalDate randomDate = d1.addDays(
ThreadLocalRandom.current().nextInt(days+1));
Related Topics
Javabean Wrapping with Javafx Properties
Java Singleton and Synchronization
Charsequence VS String in Java
How Does Java's Preparedstatement Work
How to Change Font Size in Eclipse for Java Text Editors
What Are the Pros and Cons of Performing Calculations in SQL VS. in Your Application
Keeping the Correct Style on Text Retrieval
How to Use Mdc with Thread Pools
How to Use Java to Read from a File That Is Actively Being Written To
How to Test That No Exception Is Thrown
Programmatically Change Log Level in Log4J2
JPA Onetomany Not Deleting Child
What Is the Best Way Get the Symmetric Difference Between Two Sets in Java