如何计算PHP中两个日期之间的天数?

时间:2011-03-20 15:13:06

标签: php mysql date

我需要计算从数据库获取的日期和当前日期之间的天数。

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

我该怎么做?

6 个答案:

答案 0 :(得分:3)

select datediff(curdate(),'2011-03-01');

答案 1 :(得分:2)

如果您想在PHP中执行此操作,请使用DateTime类:

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

或者是oldschool方式:

$days = round((strtotime($current) - strtotime($db_date)) /24 /60 /60);

答案 2 :(得分:1)

表格http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

SELECT DATEDIFF( CURDATE(), Date ) FROM ....

我不会使用Date作为字段名称,请考虑更改此名称

答案 3 :(得分: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

答案 4 :(得分:0)

您可以使用此格式http://php.net/manual/en/function.date.php,它会为您执行

答案 5 :(得分:0)

您可以通过以下简单方式执行此操作,

$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));