1

我正在尝试使用 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

4

5 回答 5

0

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

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

在 PHP 中只有这个:

fetch_assoc { $datediff = $row['datedifference'];
于 2013-04-02T09:28:13.453 回答
0

试试这个

echo $dateone = '02-04-13';
echo $datetwo = '06-04-13';
echo $datediff = $datetwo-$dateone;
于 2013-04-02T09:28:32.763 回答
0

SQL Query 将是理想的选择

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

PHP

$dateone = $rowdate['DiffDate'];
于 2013-04-02T09:33:30.557 回答
0

为什么不使用DateTime::diff?来源: http: //php.net/manual/en/datetime.diff.php

$datediff = $datetwo->diff($dateone);
echo $datediff;

这种差异将是时代的。您需要将其转换为您想要的格式。

于 2013-04-02T09:40:27.163 回答
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 演示。

注意: PHP 版本应 >= 5.3.0。

于 2013-04-02T09:48:46.053 回答