Eli
Eli

Reputation: 4359

Finding the difference between 2 dates

I made this and needed some help tweaking it so that it gives the proper outcome

function daysDifference($end){
    //$start = "2007-03-24";
    //$end = "2009-06-26";
    $now = date("Y-m-d");
    $e = (is_string($end) ? strtotime($end) : $end);

    $diff = abs($e - strtotime($now));

    $years = floor($diff / (365 * 60 * 60 * 24));
    $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
    $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24)/ (60 * 60 *24));

    return ($years == 0 ? '' : ($years == 1 ? $years . ' year ' : $years . ' years ')) . ($months == 0 ? '' : ($months == 1 ? $months . ' month ' : $months . ' months ')) . ($days == 0 ? '' : ($days == 1 ? $days . ' day ' : $days . ' days '));
}

$end is being pulled from my database so there is checks to see if its a string or a date already.

$e now can be used, but when I tried to subtract $now from $e I get funny results

for instance:

$now being today the 13th and $e being an end date for a project, it's suppose to give me what I need... right?

Where I'm suppose to get say 12 days remaining, I get 1 year 12 days.

and where $e = 0000-00-00 (in case the user didn't input an end date), I get 40 years 10 months and 26 days remaining.

I tried alot of different variations to my calculations but I keep getting nowhere.

Upvotes: 0

Views: 93

Answers (2)

Dan Grossman
Dan Grossman

Reputation: 52372

Store real dates, not strings, and you can just ask the database for the difference.

SELECT DATEDIFF(CURRENT_DATE, end) FROM table

If you just go dividing things by 365 you won't get accurate results. Not every year has 365 days.

Upvotes: 2

Gabi Purcaru
Gabi Purcaru

Reputation: 31524

Why would you reinvent the wheel? Use date_diff:

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
?>

Upvotes: 4

Related Questions