0

If I have two dates returned from an SQL query, how can I calculate the number of days they cover?

IE:

$date1 = '2013-08-08';
$date2 = '2013-08-12';
$days = ???;
j08691
  • 204,283
  • 31
  • 260
  • 272
Juicy
  • 11,840
  • 35
  • 123
  • 212
  • 4
    Convert the strings to [DateTime](http://php.net/manual/en/class.datetime.php) objects, and use the [diff()](http://www.php.net/manual/en/datetime.diff.php) method as shown in Example #1 on the diff() method page of the PHP documentation – Mark Baker Sep 01 '13 at 21:32
  • 1
    Valid question, with a good answer I can use in the future. +1 – Krista K Sep 01 '13 at 21:57

2 Answers2

5

As an option you can return date difference right from your sql query along with other data using DATEDIFF()

SELECT date1, 
       date2, 
       DATEDIFF(date2, date1) date_diff
  FROM ...

Sample output:

+------------+------------+-----------+
| date1      | date2      | date_diff |
+------------+------------+-----------+
| 2013-08-08 | 2013-08-12 |         4 |
+------------+------------+-----------+

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157
1

A purely php solution:

$date1= new DateTime("2013-08-08");
$date2 = new DateTime("2013-08-12");

$diff = $date1->diff($date2);

echo $diff->format("%a days ago");
adear11
  • 935
  • 6
  • 11