Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Randomy birth date

Tags:

php

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

like image 245
J.Rob Avatar asked May 15 '13 15:05

J.Rob


1 Answers

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.

like image 108
Marc B Avatar answered Sep 22 '22 09:09

Marc B