J.Rob
J.Rob

Reputation: 436

Generate Randomy birth date

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

Upvotes: 7

Views: 2556

Answers (6)

Devaldo
Devaldo

Reputation: 111

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);
}

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

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;

Upvotes: 0

Marc B
Marc B

Reputation: 360662

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.

Upvotes: 7

Orangepill
Orangepill

Reputation: 24645

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

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

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;

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

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);

Upvotes: 4

Related Questions