2016-05-10 35 views
-3

嗨,我想獲取2日期之間的日子。 這是我的編碼:如何從2日期中獲取日期php

<?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" ; 
    } 
    ?> 

,但一個錯誤就出來了:

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

請幫我謝謝

不是How to calculate the difference between two dates using PHP?

我有一個不同的副本問題在這裏,我需要事先申報嗎?

回答

2

您的$ Cur_date變量不是DateTime類的實例,它只是一個標準字符串,因此它不包含diff()方法。

嘗試改變聲明:

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

另外,爲了使用上$ newtimestamp的差異()方法,你還需要$ newtimestamp轉換爲DateTime對象。爲了使用「now」以外的日期和時間,您應該使用DateTime :: createFromFormat()靜態方法。

在你的情況下,它會是這個樣子:

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

在這一點上,你應該能夠比較兩個datetime對象,並使用diff()方法,你打算。由於您使用的是diff()方法,因此也可以使用生成的$ interval的「days」屬性而不是「d」。隨你便。

參見:
http://php.net/manual/en/datetime.diff.php
http://php.net/manual/en/datetime.createfromformat.php

+0

好TY這麼多先生 –

+0

如果此解決方案解決你的問題,如果你能親切地把它標記爲官方的答案,那簡直太好了。謝謝。 – badandyomega