Nirmal Ram
Nirmal Ram

Reputation: 1732

Date difference showing wrong values

I have used a function to calculate date difference between 2 dates.

Here is my function

function date_difference ($date_1, $date_2) {   


    $val_1 = new DateTime($date_1);
    $val_2 = new DateTime($date_2);

    $interval = $val_1->diff($val_2);
    $year     = $interval->y;
    $month    = $interval->m;
    $day      = $interval->d;

    $output   = '';

    if($year > 0){
        if ($year > 1){
            $output .= $year." years ";     
        } else {
            $output .= $year." year ";
        }
    }

    if($month > 0){
        if ($month > 1){
            $output .= $month." months ";       
        } else {
            $output .= $month." month ";
        }
    }

    if($day > 0){
        if ($day > 1){
            $output .= $day." days ";       
        } else {
            $output .= $day." day ";
        }
    }
    if($day == 0)
        $output.=' Almost Over';
    if($day < 0)
        $output.= ' Expired';
    return $output;
}

I am using it like this

echo date_difference(date('m/d/Y'),'02/06/2013');

It shows the result as 25 days where as it should show expired. Can anyone point where i am doing wrong.

Upvotes: 2

Views: 1325

Answers (3)

xdazz
xdazz

Reputation: 160843

DateInterval won't have nagative values, you need to compare the two DateTime object.

Change to

if($val_1 < $val_2 && $day == 0)
    $output.=' Almost Over';
if($val_1 > $val_2)
    $output.= ' Expired';
return $output;

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

As soon as I saw this XKCD page I wanted an opportunity to post it, and here it is!

xkcd

When your code tries to parse 02/06/2013, how can it know whether you mean "February 2nd", or "June 6th"? You should ALWAYS use the YYYY-MM-DD format when giving a date to parse, or better yet hardcode the actual numeric timestamp (in this case 1360126800)

Upvotes: 3

LUX
LUX

Reputation: 97

just use the UNIX time stamp, that way it should be a very easy calculation.

it can be shown in Y-D-M and you can even make a count down clock if you feel a bit fancy.

most MMO's and management systems use it to register the date & time of registration and to show how long the member has been on the community.

hope it helped!.

Upvotes: 1

Related Questions