I am trying to subtract two dates using php. Dateone is stored in the database while datetwo is the current date. Now, i have this strange scenario: Dateone is 23-03-13 Date two is 02-04-13
Using different subtraction methods, give different results.
Method One - Returns -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;
In this case, $datediff returns -21
Method Two - Returns -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;
In this scenario, $days returns -7639
Yeah issue is because your date format is not standard to get difference. You need to inform your current format to date & convert it to standard one to get correct difference.
$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
Note: PHP version should be >= 5.3.0.
Why not make it all in the SQL?
"SELECT time_to_sec(datediff(`exam_date`, curdate())) as datedifference FROM exam_table";
and only this in PHP:
fetch_assoc { $datediff = $row['datedifference'];
try this
echo $dateone = '02-04-13';
echo $datetwo = '06-04-13';
echo $datediff = $datetwo-$dateone;
SQL Query will be ideal for this
SELECT DATEDIFF(exam_date,CURDATE()) AS DiffDate FROM exam_table
PHP
$dateone = $rowdate['DiffDate'];
Why not use DateTime::diff
? Source : http://php.net/manual/en/datetime.diff.php
$datediff = $datetwo->diff($dateone);
echo $datediff;
This difference will be in epoch. You would need to convert it to your desired format.