问题
Possible Duplicate:
php date compare
I have a date that I take from the mySQL database that looks like this:
2011-06-20
And I get the date of the current day in this way:
$todaydate = date('Y-m-d');
What I need to know is how do I compare the two results?
How can I compare the dates and understand for example if a week is passed from the database date or a month or a year..etc..?
Thank you!!
回答1:
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()
returnsexpr1
–expr2
expressed as a value in days from one date to the other.expr1
andexpr2
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.
回答2:
How about considering using UNIX_TIMESTAMP? It uses the concept of elapsed time.
回答3:
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.
回答4:
And of course date_diff has plenty of examples.
回答5:
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.
回答6:
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.
来源:https://stackoverflow.com/questions/6405910/php-compare-dates