0

I am using the following code to get the difference between two dates. I'm having issues with it returning the correct amount of days left.

<?php 
$nextservicedate = FrmProDisplaysController::get_shortcode( array( 'id' => 3451 ) );
$currentdate = date("d/m/Y");
$daysremaining = $nextservicedate - $currentdate;
echo $nextservicedate. " | ";
    if ( strpos($nextservicedate, 'None registered') !== false )

    {
        echo "None Registered";
    }
    elseif ($daysremaining < "0")
    {
        $negativedays = str_replace('-', ' ', $daysremaining);
        echo $negativedays. " days overdue";
    }
    elseif ($daysremaining <= "30")
    {
        echo $daysremaining. " days (upcoming service)";
    }
    else
    {
        echo $daysremaining. " days";
    }
?>

The entry

FrmProDisplaysController::get_shortcode( array( 'id' => 3451 ) )

returns a date from a wordpress form plugin (FormidablePro) as 30/10/2016.

The code is returning there are 23 days remaining which I believe is taking it to the end of this month.

I know I'm missing something and think it probably has something to do with the working out the days remaining part of the code.

Can anyone see any glaring errors? Do I need to declare the $nextservicedate like I've done with $currentdate?

Any help would be greatly recieved!

Regards

Matt

Matthew Barraud
  • 467
  • 1
  • 5
  • 17

1 Answers1

1

PHP's date() returns date string which cannot be used to perform arithmetic operations on date.

What you need to do is create DateTime object of service date from String using createFromFormat() and create current DateTime() object.

Then use diff() function of DateTime object to find the difference between two days.

So your code would look something like this,

$nextservicedate=DateTime::createFromFormat("d/m/Y",$nextservicedate);
$todaydate=new DateTime();
$difference=$nextservicedate->diff($todaydate);

To get the difference in days,

echo $difference->format('%R%a days');
Alok Patel
  • 7,842
  • 5
  • 31
  • 47