-3

hi i'm trying to get the days between 2 dates. this is my coding:

<?php
    $Cur_date = date("Y-m-d");
    $Warranty = intval($row_Recordset1['Hardware_warranty']);
    $timestamp = strtotime($row_Recordset1['Pur_date']);
    $newtimestamp = strtotime("+".$Warranty." years", $timestamp);
    $newtimestamp = date('Y/m/d', $newtimestamp) ;



   if($Cur_date< $newtimestamp)
   {
        $interval = $Cur_date->diff($newtimestamp);
        echo "Valid"."\n\n\n".$interval->y . " years, " . $interval->m." months, ".$interval->d." days "." left";
   }
   else if ($Cur_date > $newtimestamp)
   {
        echo "Expired" ;   
   }
   ?>

but an error came out:

Fatal error: Call to a member function diff() on string in C:\xampp\htdocs\Warranty\WarrantyStatus.php on line 155

please help me thank you

not a duplicate of How to calculate the difference between two dates using PHP?

i'm having a different problem here,do i need to declare something beforehand?

Community
  • 1
  • 1

1 Answers1

2

Your $Cur_date variable isn't an instance of the DateTime class, it's just a standard string, so it doesn't contain a diff() method.

Try changing the declaration to:

$Cur_date = new DateTime("Y-m-d");

Also, in order to use the diff() method on $newtimestamp, you'll also need to convert $newtimestamp to a DateTime object. In order to use a date and time other than "now", you should use the DateTime::createFromFormat() static method.

In your case, it would look something like this:

$Warranty = intval($row_Recordset1['Hardware_warranty']);
$timestamp = strtotime($row_Recordset1['Pur_date']);
$newtimestamp = strtotime("+".$Warranty." years", $timestamp);
$newtimestamp = DateTime::createFromFormat('Y/m/d', $newtimestamp);

At this point, you should be able to compare the two DateTime objects, and use the diff() method as you intended. Since you are using the diff() method, you can also use the "days" property of the resulting $interval instead of "d". It's up to you.

See also:
http://php.net/manual/en/datetime.diff.php
http://php.net/manual/en/datetime.createfromformat.php

badandyomega
  • 252
  • 1
  • 4