Projects

Mini Age Calculator With PHP OOPs [+Source Code]

Share your learning

Hey, are you a beginner in PHP? Just finished your basic of PHP and OOPs?

Do you want something interesting to build?

Have you ever tried an age calculator with PHP?

Here I am with a nice-looking age calculator with PHP OOPs.

Yes, it’s not tough to calculate the difference between two dates. It can be achieved with some simple lines of code.

In Procedural Way

echo date_diff(date_create($bday), date_create('today'))->y;

In OOPs Way

$birthDate = new DateTime('1996-04-19');
$today   = new DateTime('today');
echo $birthDate->diff($today)->y;

I have something extra for you, so continue reading.

What’s OOPs?

Read a detailed article on OOPs here.

What we are going to build?

So, let’s start the interesting part. But first, look at the output.

Final output

You can confirm the final result here https://www.calculator.net/age-calculator.html,

What we are going to use?

  1. PHP OOPs
  2. Bootstrap
  3. Jquery
  4. Bootstrap-DatePicker

So, let’s dive into it,

Create some layout files

Header and Footer are the two file which we are added here.

The header file is to link external CSS and Js. Footer file is to link and trigger Js.

Header

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    
    <!-- Add page icon -->
    <link rel="icon" href="assets/icon/sb.png" type="image/png" sizes="16x16" /> 
    <title>Age calculator</title>
    
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" />
    
    
    <!-- Latest compiled and minified JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    
    <!-- Add external css  -->
    <link rel="stylesheet" href="assets/css/theme.css" />
</head>
<body>

Footer

<script type="text/javascript">
         $('.datepicker').datepicker({
            format: 'dd-mm-yyyy',
            autoclose: true,
            todayBtn: true,
            todayHighlight: true,
        });
    </script>
</body>
</html>

You can read about the best position of Js file in HTML document, here.

Create Age Class

<?php

Class Age {
    public $dateOfBirth;
    public $today;
    public $age;

    public function __construct($dob) {
        $this->dateOfBirth = new DateTime($dob); 
        $this->today = new DateTime('today');  
    }

    public function ageCalculation() {
        $this->age =  $this->dateOfBirth->diff($this->today);
    }
}


?>

Index file

It will connect the all dots like header, footer and age class file also.

We are using include once function instead of include read the difference here.

<?php
    include_once('age.php');

    if(isset($_POST['dob'])){
        $person = new Age($_POST['dob']);
        $person->ageCalculation();
    }
?>
<!-- Add header(link stylesheets, jquery, bootstrap) -->
<?php include_once('layout/header.php'); ?>

<div class="container">
        <div class="page-header">
            <h1>Age calculator</h1>
        </div>
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="panel panel-default theme-color mt-1">
                    <!-- Default panel contents -->
                    <div class="panel-heading theme-color text-center"><span class="glyphicon glyphicon-calendar"></span> Age Calculator</div>
                    <div class="panel-body">
                        <form class="form-inline text-center" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                            <div class="form-group">
                                <input type="text" name="dob" class="form-control datepicker" placeholder="Select Date of Birth" 
                                    <?php if(isset($_POST['dob'])) { ?>value="<?= $person->dateOfBirth->format('d-m-Y'); ?>"<?php } ?>
                                />
                            </div>
                            <div class="form-group">
                                <button type="submit" class="form-control btn btn-dark"><span class="glyphicon glyphicon-check"></span> Calculate</button>
                            </div>
                        </form>
                        <div class="mt-1">
                            <?php if(isset($_POST['dob'])) { ?>
                                <div class="alert alert-warning alert-dismissible text-center" role="alert">
                                    
                                    Today is <?= $person->today->format('d-m-Y'); ?>
                                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                        <span aria-hidden="true">×</span>
                                    </button>
                                </div>
                                <div class="alert alert-success text-center" role="alert">
                                    The age is <?= $person->age->y ?> years <?= $person->age->m ?> months <?= $person->age->d ?> days old
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                    <div class="panel-footer theme-color text-center">Powered by <a class="link-color" href="https://sbsharma.com" target="_blank">www.sbsharma.com</a></div>
                </div>
            </div>
        </div>
        
    </div>
    
<!-- Add footer(js scripts) -->
<?php include_once('layout/footer.php'); ?>

Sum-up

This strategy will also help you to integrate a pre-built theme with PHP and its frameworks. So, understand carefully.

Obviously bootstrap helps us to minimize our custom CSS, that’s why we have used it.

That’s it.

Start your local server if you are working on local and test your code.

Here is an assignment for you, add the custom date to calculate age instead of the current date.

If you face any kind of problem or found any issue with above code. Please feel free to comment.

Get source code

Click below button to clone the source code from git-hub repository.

Satpal

View Comments

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago