使用 strtotime 计算天数返回错误结果
我有两个日期存储在 mysql 数据库中(类型 = 日期)。例如 -
日期 1 = 2010-09-20
日期 2 = 2010-10-20
我想计算这两个日期之间的天数。所以已经尝试过这个 -
$number_days = (strtotime($date2) - strtotime($date1) / (60 * 60 * 24));
但这返回 49
怎么会呢?
- - - - - - - - - - - - - - - - - - - 更新 - - - - - - ------------------------------
好吧,我意识到我的问题导致了一些混乱。我正在使用另一个函数来检索日期 1,由于各种原因,该日期没有正确返回,因此给出的天数实际上是正确的。当我从数据库中检索到正确的日期时,我上面的计算起作用了,考虑到了 / 的优先级 -
感谢您的回复。
I have two dates stored in a mysql database (Type = date). For example -
Date 1 = 2010-09-20
Date 2 = 2010-10-20
I 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 this 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
/
具有更高的优先级
< /a> 比-
所以
(a - b / c)
将被视为( a - (b/c) )
但你需要的是( (a - b) / c )
所以尝试:
/
has higherprecedence
than-
So
(a - b / c)
will be treated as( a - (b/c) )
but what you need is( (a - b) / c )
So try:
您可以使用 MySql 查询
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_to-days
You can do this with MySql query
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_to-days
如果您从 MySQL 数据库获取这两个日期,我总是发现在 SQL 查询期间将它们转换为 UnixDateTime 整数格式更容易。以这种格式处理它们要容易得多。
你的查询看起来像这样:
我总是发现这样做比以字符串形式获取日期然后不得不搞乱 PHP 笨重的日期处理函数要好得多。
也就是说,日期类在 PHP5.3 中要好得多——它甚至具有日期加/减函数,这也比 strtotime() 更好地解决您的问题...假设您使用的是 PHP 5.3。
希望有帮助。但我知道这并不能直接回答问题!
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:
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!