-2

I want to calculate the percentage (from 0 to 100) of the time elapsed between two dates (start and end) according to the current date. For example:

$start_date = "01/01/2018";
$end_date = "31/12/2018";
$today = "30/06/2018";

Expected output:

Percentage: 50

Any idea? Thanks

Andreas
  • 23,610
  • 6
  • 30
  • 62
Alfonso
  • 67
  • 5
  • https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php and from difference make percentage. – Zydnar Nov 16 '18 at 19:48
  • Is start and end always start and end of the current year? – Andreas Nov 16 '18 at 20:01
  • Perform a datedifference(today, date1) / datedifference(date2, date1). Multiply by 100. – Salman A Nov 16 '18 at 20:08
  • 1
    Possible duplicate of [How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Per Lundberg Nov 16 '18 at 21:29

3 Answers3

4

You could convert all dates to timestamps and do the math from there. strtotime() will convert the dates for you, but that will interpret your dates with slashes in the english format (MM/DD/YYYY) instead of (DD/MM/YYYY). If you replace the slashes with dashes, it will read it in the DD-MM-YYYY format.

$date_timestamp = strtotime(str_replace('/', '-', $date));

Then it's just a matter of:

$total = $end_date - $start_date;
$part = $todays_date - $start_date;
$percent = $part/$total * 100;
khartnett
  • 831
  • 4
  • 14
3

You'd need at least three variables:

$fromDate = strtotime("01/01/2018 ");
$currentDate = time();
$toDate = strtotime("01/01/2019");



//days between From and To
$datediffA = round(($toDate- $fromDate) / (60 * 60 * 24));
//days between From and Current
$datediffB =  round(($currentDate- $fromDate) / (60 * 60 * 24));

echo $datediffA;

echo $datediffB;

Will output:

365

320

Now knowing these numbers you can go on and find the percentage of one to another.

$percentage = ($datediffB*100)/$datediffA;

echo $percentage;

Will output:

87.671232876712%

Rantanen
  • 156
  • 5
0

Date("z") gives you the day of the year.
Your "today" returns 180.

If we assume start and end is the start and end of current year then all you need is the date("z") to calculate the percentage.
Round the value to desired format and echo the percentage.

$today ="30/06/2018";
echo round(date("z", strtotime(str_replace("/", "-", $today)))/365*100,0) . "%";
// 49%

https://3v4l.org/EG6lt

I assume 365 days is enough accurate as a year.
You can use 365 + date("L") instead of only 365 in the code above and it will add one if it's a leap year. Meaning:

echo round(date("z", strtotime(str_replace("/", "-", $today)))/(365 + date("L"))*100,0) . "%";
Andreas
  • 23,610
  • 6
  • 30
  • 62