How to calculate days between two dates in PHP?

I need to calculate the days between the date I get from the database and the current date.

$upload_date = mysql_query("SELECT Date FROM Setting WHERE ID = $row[ID]");
$current_date = date("Y-m-d");

How should I do it?

+3
source share
6 answers
select datediff(curdate(),'2011-03-01');
+3
source

If you want to do this in PHP, use the DateTime class :

$current = new DateTime($current_date);
$db_date = new DateTime($upload_date);
$days = $current->diff($db_date)->days;

Or the oldschool path:

$days = round((strtotime($current) - strtotime($db_date)) /24 /60 /60);
+2
source
+1

SELECT DATEDIFF ('new_date', 'old_date');

mysql> SELECT DATEDIFF('2006-04-01','2006-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2006-04-01') |
+-------------------------------------+
|                                   0 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2006-04-01','2007-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2007-04-01') |
+-------------------------------------+
|                                -365 |
+-------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT DATEDIFF('2006-04-01','2005-04-01');
+-------------------------------------+
| DATEDIFF('2006-04-01','2005-04-01') |
+-------------------------------------+
|                                 365 |
+-------------------------------------+
1 row in set (0.00 sec)

DATEDIFF (, 2)

DATEDIFF() expr expr2. expr expr2 - . .

mysql> SELECT DATEDIFF('1997-12-31 23:59:59','1997-12-30');
    -> 1
mysql> SELECT DATEDIFF('1997-11-30 23:59:59','1997-12-31');
    -> -31
+1

You can use this format http://php.net/manual/en/function.date.php and it will do it for you

0
source

you can do it in a simple way as shown below

$current_date = date("Y-m-d");          // Current date
$db_date = date("Y-m-d");               // Date from your database
$diff = abs(strtotime($current_date) - strtotime($db_date));
$total_days = floor ($diff /  (60*60*24));
0
source

All Articles