PHP date() 和 strtotime() 返回错误的月份 31 日
我使用 date()
和 strtotime()
函数在下拉列表中显示接下来的 3 个月。
PHP 代码:
echo date("m/Y",strtotime("+0 months"));
echo date("m/Y",strtotime("+1 months"));
echo date("m/Y",strtotime("+2 months"));
但是,如果脚本在服务器日期为 30 日或 31 日时运行,则下个月(二月)将显示为三月。 即上面的脚本应该返回
01/2012
02/2012
03/2012
但是,它实际上显示
01/2012
03/2012
03/2012
的是因为二月没有 30 日或 31 日,所以脚本将“31/02”翻译为“01/03”。
我读过php.net上的strtotime()
页面,已经提出了这个问题,但还没有任何有用的解决方案。那么有人可以帮我找到一个简单的方法来解决这个问题吗?提前致谢!
I'm using date()
and strtotime()
functions to display the next 3 months in a dropdown list.
PHP Code:
echo date("m/Y",strtotime("+0 months"));
echo date("m/Y",strtotime("+1 months"));
echo date("m/Y",strtotime("+2 months"));
However, if the script is running when the server date is on 30th or 31st, the next month, which is Feburary, will be displayed as March instead.
i.e. the script above is supposed to return
01/2012
02/2012
03/2012
But, instead of that, it actually displays
01/2012
03/2012
03/2012
that is because Feburary doesn't have 30th or 31st, so the script translates "31/02" into "01/03".
I have read the strtotime()
page on php.net, this problem has been raised, but there has not been any useful solutions. So can anyone please help me to find a simple way to solve this problem? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如文档中所述,您应该将当月第一天的日期作为第二个参数传递给
strtotime()
函数:查看它是否有效:http://ideone.com/eXis9
As mentioned within the documentation, you should pass the date for the first day of the current month as the second parameter to the
strtotime()
function:See that it works: http://ideone.com/eXis9
尝试在 strtotime 中使用“第一天”,如下所示:
这将修复日期(如果今天是 1 月 30 日),例如 02-30(3 月 2 日产量),方法是将其转换为 02-01(2 月 1 日),然后为您提供正确的月份。它比其他方法更简洁,也更容易记住。
Try using "first day of" in your strtotime, like this:
This will fix dates ( in the event today was Jan 30th ) such as 02-30 (Yields march 2nd) by converting it to 02-01 (Feb 1st) which then gives you the correct month. It's a little cleaner than other methods, and easier to remember.
只需将其硬编码为该月的第一天即可。
Just hard-code it to be the first of the month.
不要使用 strtotime() 来按月获取偏移日期。它仅在 PHP 5.3+ 中正常工作。
解决此类问题的最佳方法是使用 mktime()。
下面是示例代码:
Don't use strtotime() for getting offset date by month(s). It works properly only in PHP 5.3+.
The best way to solve such problem is using mktime().
Below is a sample code: