PHP Calculate Percentage Remain Between Two Dates


This has been a favorite of mine and I am happy to share with you. In this tutorial I will show you how to get the percentage from the start date to time remaining using PHP.
This is very useful and in my case is used in the Joomla Subscription component where I would like to display to the user a progress bar with the percentage remaining in their subscription.

There are three dates we need, the start date, the end date and of course the current date so make sure to store both the start and end date in the database.

Step 1
The first step is to collect our dates and convert them to a DateTime object, in my example I am getting the start and end date from a database (expire, created)

    $start = new DateTime($item->created);
    $end = new DateTime($item->expire);
    $today = new DateTime('now');

Step 2
Next we get the difference between the start and end and also the difference between the start and today.

    $total = $start->diff($end);
    $current = $start->diff($today);

Step 3
Finally we calculate the percentage using the days difference multiplied by 100.

$percent_completed = round($current->days / $total->days * 100, 1);

That’s it. I hope you find this tutorial helpful, leave a comment and also join us on Twitter!

Please Post Your Comments & Reviews

Welcome to Western Studios

We provide professional website and mobile softwares including Joomla, Wordpress and more.