PHP compare dates [duplicate]

此生再无相见时 提交于 2019-12-02 00:43:55

There is no need to put that burden on PHP when MySQL has built-in functionality for that already. You should take a look at MySQL's DATEDIFF() function:

DATEDIFF() returns expr1expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

An example of two dates that'd give a 7-day difference could be:

mysql> select datediff('2011-06-18','2011-06-25');
+-------------------------------------+
| datediff('2011-06-18','2011-06-25') |
+-------------------------------------+
|                                  -7 | 
+-------------------------------------+

This means that the first date occured -7 days after the first date; that's 7 days before. If you let the two arguments switch place, the result would be a positive 7.

How about considering using UNIX_TIMESTAMP? It uses the concept of elapsed time.

The "old" way to compare two or more dates is to convert then to an unix timestamp (seconds in float) using strtotime() function. For example:

if((strtotime('2011-05-10') - strtotime('2011-05-01')) > 604800)
{
    echo('A week has passed');
}

if((strtotime('2011-06-10') - strtotime('2011-05-01')) > 2629743)
{
    echo('A month has passed');
}

Or the "new" way is to use the DateTime class bundled with PHP 5.2 or newer. Have a look at http://php.net/manual/en/book.datetime.php.

And of course date_diff has plenty of examples.

You need to consider what you are exactly looking for.

  • Are you looking to filter dates older than a week? You can do that comparison on the SQL and you don't burden PHP with date comparisons.

  • Are you wanting a date difference? Again, I suggest putting it in SQL and just display the result.

This will give you the number of seconds between the two dates:

<?php
$time = '2011-06-20';
$timeDiff = time() - strtotime($time);
echo $timeDiff;
?>

You could divide this value by 86,400 to get the number of days, and so on.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!