Calculate your age with PHP

Calculate your age with PHP

Sometimes you might want to hide the user's birth date and you only want to show their age. I have encountered something similar so I want to share how I did it.

PHP provides many methods for showing and editing date and time. In this case I will be using date(), date_create() and date_diff().

Since there is already a few tutorials on this topic, I don't want to repeat the same thing, so I will try to add some fun stuff here, like letting the user enther his/her birth date and then showing them the age.

First let's write some boilerplate HTML and add a form with a date input field.

<!DOCTYPE html>
<html>

<body>

    <form action="form.php" method="post">
        <label for="bDate">Birth date</label>
        <input type="date" id="bDate" name="birth_date" required style="margin: 10px;">
        <br>
        <input type="submit" value="Calculate">
    </form>

</body>

</html>

It should look like this:

birthdate form.png

Next, in your form.php add the following code:

<?php

if (isset($_POST['birth_date'])) {

    $date_of_birth = $_POST['birth_date'];

    $today_date = date("d-m-Y");
    $diff = date_diff(date_create($date_of_birth), date_create($today_date));
    $age = $diff->format('%y');   

    echo 'You are ' . $age . ' years old.';

}

?>

We are checking if the value is actually there with isset() method and then we are calculating the date with date_diff() method and storing it into $diff variable. After that we are formatting it by passing '%y' parameter to format() method, so it can extract the year from date.

Now, when you enter your birth date, it should show you the correct response with your age.

You can get the code from this github repo.