Home » Php » php – Generate Randomy birth date

php – Generate Randomy birth date

Posted by: admin July 12, 2020 Leave a comment

Questions:

This is my code:

$curr_year = date('Y');
$dob_year  = rand($curr_year-18,$curr_year-47);
$dob_month = rand(01,12);
$dob_day   = rand(01,30);

echo $dob = $dob_month.'/'.$dob_day.'/'.$dob_year;

And I am getting result as 1/2/1988, but my requirement is result should be 01/02/1988

How to&Answers:

Use str_pad.

echo $dob = str_pad($dob_month, 2, '0', STR_PAD_LEFT) . '/' . str_pad($dob_day, 2, '0', STR_PAD_LEFT) . '/'.$dob_year;

Answer:

How about:

$min = strtotime("47 years ago")
$max = strtotime("18 years ago");

$rand_time = mt_rand($min, $max);

$birth_date = date('%m/%d/%Y', $rand_time);

Basically: generate a couple of unix timestamps that represent your allowable date rage, then use those timestamps as the min/max ranges of the random number generator. You’ll get back an int that just happens to be usable as a unix timestamp, which you can then feed into the date() and format however you’d like.

This has the added benefit/side-effect of allowing you to get a randomized birth TIME as well, not just a date.

Answer:

In this particular case, you can use sprintf:

echo sprintf("%02s/%02s/%04s",$dob_month,$dob_day,$dob_year);

However, I would suggest handling dates as dates:

$min = strtotime("jan 1st -47 years");
$max = strtotime("dec 31st -18 years");
$time = rand($min,$max);
echo $dob = date("d/M/Y",$time);

Answer:

You can use sprintf, str_pad, or date with strtotime to get you what you want.

Another this to note is in your code you are making the statement

rand(01,12);

and with the leading 0 it is being interpreted as an octal number. In this case it’s not an issue becuase 01 == 1 but if you where trying to get a month in the last quarter, 09 is an invalid octal number and php will interpret it as 0. See the warning at http://php.net/manual/en/language.types.integer.php for details

Answer:

Use str_pad –> Manual

$dob = str_pad($dob_month, 2, '0', STR_PAD_LEFT).'/'. str_pad($dob_day, 2, '0', STR_PAD_LEFT).'/'.$dob_year;
echo $dob;

Answer:

I had the same need, get a random date. So here is my solution. Generate absolutly valid date.

// Random birthdate between age
function get_random_birthdate_by_age($min_age, $max_age)
{
    $age = rand($min_age, $max_age);
    $birth_year = date("Y") - $age; // Current year - age
    return date("d.m.Y", strtotime("01.01.{$birth_year} +" . rand(0, 365) . " days"));
}

// Random birthdate between age 0 - 110
function get_random_birthdate()
{
    return get_random_birthdate_by_age(0, 110);
}