calculating the number of days using strtotime returns wrong result
I have two dates stored in a mysql database (Type = date). For example -
Date 1 = 2010-09-20
Date 2 = 2010-10-20I want to calculate the number of days between these two dates. So have tried this -
$number_days = (strtotime($date2) - strtotime($date1) / (60 * 60 * 24));
But th开发者_运维技巧is returns 49
How so?
------------------------------------- UPDATE ------------------------------------------
Ok I realised my problem which was causing some confusion. I was using another function to retrieve date 1 and for various reasons this date was not being returned correctly so the number of days given was actually correct. When I retrieved the correct date from the database my calculation above worked, taking in to account the precedence of / over -
thanks for your responses.
/
has higher precedence
than -
So (a - b / c)
will be treated as ( a - (b/c) )
but what you need is ( (a - b) / c )
So try:
$number_days = (strtotime($date2) - strtotime($date1)) / (60 * 60 * 24);
You can do this with MySql query
SELECT (TO_DAYS( date1 ) - TO_DAYS( date2 )) as difference FROM MyTable
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_to-days
If you're fetching both dates from a MySQL database, I've always found it easier to conver them to UnixDateTime integer format during the SQL query. They're much easier to handle in that format.
Your query would look something like this:
SELECT *, UNIX_TIMESTAMP(date1) date1_u, UNIX_TIMESTAMP(date2) as date2_u from mytable
I've always found it much better to do that than to get the dates as strings and then have to mess with PHP's clunky date handling functions.
That said, the date class is much better in PHP5.3 -- it even has date add/subtract functions, which would also solve your problem much better than strtotime()... assuming you're using PHP 5.3.
Hope that helps. I know that doesn't directly answer the question, though!
精彩评论