简体   繁体   English

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

[英]How to calculate days between two dates in PHP?

I need to calculate days between a 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 do I do it? 我该怎么做?

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

If you want to do it in PHP, then use the DateTime class: 如果您想在PHP中执行此操作,请使用DateTime类:

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

Or the oldschool way: 或者是oldschool方式:

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

Use SELECT DATEDIFF('new_date', 'old_date'); 使用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(expr,expr2) DATEDIFF(表达式,表达式2)

DATEDIFF() returns the number of days between the start date expr and the end date expr2. DATEDIFF()返回开始日期expr和结束日期expr2之间的天数。 expr and expr2 are date or date-and-time expressions. expr和expr2是日期或日期和时间表达式。 Only the date parts of the values are used in the calculation. 在计算中仅使用值的日期部分。

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

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

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

and I would not use Date as field name, consider to change this name 我不会使用Date作为字段名称,请考虑更改此名称

you can do this in a simple way as 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));

你可以使用这种格式http://php.net/manual/en/function.date.php ,它会为你做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM