I encountered a problem last time about solving for the age of a certain member based on the member’s birthday and the date today. I’ve found several codes that can do this but the only problem is it only displays the difference between years and excluded the month which yields a wrong result. Let’s say the current date today is April 15, 2016 and the member’s birthday is October 14, 1989. The age should be 26 and not 27.
So here is the code that solves for the right age of a member base on member’s birthday inputted by a user. I will explain the code for you to understand. The first date_create contains the birthday of a member from the textbox value while the second date_create contains the current computer date using the difffunction. The diff function will solve for the difference between the two (2) dates and will return value in year.
PHP Code for simple age calculator
<!DOCTYPE html>
<head>
<body>
<form method="post">
<input type="date" name="bday">
<input type="submit" name="calc" value="Calculate">
</form>
<?php
if (isset($_POST['calc']))
{
$bday=$_POST['bday'];
$age = date_create($bday)->diff(date_create('today'))->y;
echo "Your birthday is $bday and you are ".$age." years old";
}
?>
</body>
</html>
Sample output for simple age calculator
The purpose of the isset($_POST['calc']) is to make sure that the user will input a value in the textbox and click the calculate button before executing the php script to avoid errors due to null value.
Hope this helps! ^_^
No comments:
Post a Comment