我想用php减去两个日期。 Dateone存储在数据库中,而datetwo是当前日期。 现在,我有这种奇怪的情况: Dateone是23-03-13 第二天是02-04-13
使用不同的减法方法,给出不同的结果。
方法一 - 返回-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;
在这种情况下,$ days返回-7639
答案 0 :(得分:0)
为什么不在SQL中全部使用?
"SELECT time_to_sec(datediff(`exam_date`, curdate())) as datedifference FROM exam_table";
仅在PHP中使用:
fetch_assoc { $datediff = $row['datedifference'];
答案 1 :(得分:0)
试试这个
echo $dateone = '02-04-13';
echo $datetwo = '06-04-13';
echo $datediff = $datetwo-$dateone;
答案 2 :(得分:0)
SQL查询将是理想的
SELECT DATEDIFF(exam_date,CURDATE()) AS DiffDate FROM exam_table
<强> PHP
$dateone = $rowdate['DiffDate'];
答案 3 :(得分:0)
为什么不使用DateTime::diff
?资料来源:http://php.net/manual/en/datetime.diff.php
$datediff = $datetwo->diff($dateone);
echo $datediff;
这种差异将在时代。您需要将其转换为所需的格式。
答案 4 :(得分: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
注意: PHP版本应为&gt; = 5.3.0。