Today we are going to see another useful and interesting PHP script which you may use it in your project as well. That is finding age from your DOB or any given date.
See the demo here,
Let’s see the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?php //this function return two main values status (either true or false) and result (which has all the other details) function find_age($dob){ $response = new stdClass(); //using try catch in case if any invalid date entered try{ //get the entered dob and current datetime $date = new DateTime($dob); $now = new DateTime(); //validate if the entered year is not greater than current year if(strtotime($dob) > time()){ $response->status = false; $response->result = 'Please enter past date!'; return $response; } //here is the real deal, diff() is the function which is going to give us the result $dateInterval = $now->diff($date); $response->status = true; $response->result = $dateInterval; return $response; }catch(Exception $e){ $response->status = false; $response->result = 'Invalid Date Format'; return $response; } } ?> <html> <head> <title>PHP Script to Find age from Date of Birth</title> </head> <body> <h3>Find age from Date of Birth</h3> <form method="post"> Enter your DOB: <input type="date" name="dob" placeholder="eg:16-05-1987" value="<?=(isset($_POST['dob']))? $_POST['dob']: '';?>" /> <input type="submit" value="Find Age" /><br /><br /> <?php //check if the post data has some value if(isset($_POST['dob']) && $_POST['dob']){ $dob = $_POST['dob']; //now call the function $find_age = find_age($dob); if($find_age->status){ echo $find_age->result->y.' Years '. $find_age->result->m. ' Months and '. $find_age->result->d . ' days'; }else{ echo $find_age->result; } } ?> </form> </body> </html> |
Read the comments in the above script to understand it.