Create a random date of birth

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 get the result as 1/2/1988 , but my requirement is the result 01/02/1988

+6
source share
6 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; 
+1
source

In this particular case, you can use sprintf :

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

However, I suggest treating 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); 
+4
source

What 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 pair of unix timestamps that represent a valid date rage, and then use these timestamps as the minimum / maximum ranges of the random number generator. You will return to int, which, as it turned out, will be used as a unix timestamp, which you can then feed into the date() format and the format you need.

This has the added benefit / side effect of allowing you to receive a randomized TIME TIME, not just a date.

+3
source

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

Another thing to note in the code you are doing.

 rand(01,12); 

and with a leading of 0, it is interpreted as an octal number. In this case, this is not a problem because 01 == 1, but if you try to get the month in the last quarter, 09 is an invalid octal number, and php will interpret it as 0. See Warning at http://php.net /manual/en/language.types.integer.php for details

+1
source

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; 
0
source

I had the same need to get a random date. So here is my solution. Create an absolutely reliable 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("dmY", 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); } 
0
source

Source: https://habr.com/ru/post/945078/


All Articles