2013-04-02 57 views
1

我想用php减去两个日期。 Dateone存储在数据库中,而datetwo是当前日期。 现在,我有这个奇怪的场景: Dateone是23-03-13 日期二是13年2月4日Php用不同的日期减去两个日期返回错误的结果

采用不同的方法减,得出不同的结果。

方法一 - 返回-21

$sqldate ="SELECT exam_date FROM exam_table"; 
$fetchdate = mysql_query($sqldate); 
$rowdate = mysql_fetch_array($fetchdate); 
//Fetch the date stored in the database 
$dateone = $rowdate['exam_date']; 
//Calculate the current date today 
$datetwo =date('d-m-y'); 
//Calculate the diff between the two dates 
$datediff = $datetwo-$dateone; 

在这种情况下,$ DATEDIFF返回-21

方法二 - 返回-7639

$sqldate ="SELECT exam_date FROM exam_table"; 
$fetchdate = mysql_query($sqldate); 
$rowdate = mysql_fetch_array($fetchdate); 
//Fetch the date stored in the database 
$dateone = $rowdate['exam_date']; 
//Calculate the current date 
$datetwo =date('d-m-y'); 
//Calculate the diff between the two dates 
$datetime1 = strtotime("$dateone"); 
$datetime2 = strtotime("$datetwo"); 
//seconds between the two times 
$secs = $datetime2 - $datetime1; 
$days = $secs/86400; 

在这种情况下,$天返回-7639

+0

我假设其中一个日期比另一个大。在运行时打印它们并查看。 – MahanGM

+0

在第二个中,您使用$ datetoday,但转换为使用$ datetwo的时间。请在运行时写出$ dateone的结果,然后写出$ datetwo的结果,以便我们可以真正看到结果。 – karmafunk

+0

**方法二**中的$ datetwo'在哪里? – egig

回答

0

是的问题是因为你的日期格式不是标准的差异。您需要通知您目前的格式&将其转换为标准格式以获得正确的区别。

$datetime1 = DateTime::createFromFormat('d-m-Y', '23-03-13'); #In you case it is considering 13-03-2023 
$datetime1->format('d-m-YY'); 
$datetime2 = DateTime::createFromFormat('d-m-Y', '02-04-13'); #In you case it is considering 13-04-2002 
$datetime2->format('d-m-YY'); 
$interval = $datetime1->diff($datetime2); 
echo $interval->format('%R%a days'); #output +10 days 

CodeViper Demo.

注: PHP版本应该是> = 5.3.0。

+0

这很好,如果我想将差异存储在一个变量? – mutiemule

+0

@Joseph - 而不是回声分配给一个变量。 – Rikesh

+0

请演示。 – mutiemule

0

为什么不把它全部放在SQL中?

"SELECT time_to_sec(datediff(`exam_date`, curdate())) as datedifference FROM exam_table"; 

只有这在PHP中:

fetch_assoc { $datediff = $row['datedifference']; 
0

试试这个

echo $dateone = '02-04-13'; 
echo $datetwo = '06-04-13'; 
echo $datediff = $datetwo-$dateone; 
+0

这工作得很好,但问题在于月份有所不同。在你的场景中,如果dateone是02-04-13而datetwo是06-05-13,那么结果将会非常不同。 – mutiemule

0

SQL查询将是非常理想的

SELECT DATEDIFF(exam_date,CURDATE()) AS DiffDate FROM exam_table 

PHP

$dateone = $rowdate['DiffDate']; 
+0

这可行,但它给出的结果为3632.问题是什么? – mutiemule

+0

你想如何区别?几小时还是几秒?所以我可以调整代码。 –

+0

请在几天内。 – mutiemule