问题描述
我一直在使用 DateTime 类
并且最近在添加月份时遇到了我认为的错误.经过一番研究,它似乎不是一个错误,而是按预期工作.根据此处的文档:
示例#2 添加或添加时要小心减去月份
modify('+1 个月');echo $date->format('Y-m-d') ."
";$date->modify('+1 个月');echo $date->format('Y-m-d') ."
";?>
上面的例子会输出:2001-01-312001-03-03
谁能证明为什么这不被视为错误?
此外,有没有人有任何优雅的解决方案来纠正问题并使其 +1 个月按预期工作而不是按预期工作?
为什么它不是错误:
当前的行为是正确的.以下发生在内部:
+1 month
将月份数(原为 1)加 1.这使得日期2010-02-31
.第二个月(二月)在 2010 年只有 28 天,因此 PHP 会通过继续计算从 2 月 1 日开始的天数来自动更正这一点.然后你会在 3 月 3 日结束.
如何得到你想要的:
要得到你想要的东西是:手动检查下个月.然后加上下个月的天数.
我希望你可以自己编写代码.我只是在提供该做什么.
PHP 5.3 方式:
要获得正确的行为,您可以使用 PHP 5.3 的一项新功能,该功能引入了相对时间节 first day of
.本节可以与下个月
、第五个月
或+8个月
结合使用以转到指定月份的第一天.您可以使用此代码获取下个月的第一天,而不是 +1 个月
,如下所示:
modify('下个月的第一天');echo $d->format( 'F' ), "
";?>
此脚本将正确输出February
.当 PHP 处理这个下个月的第一天
节时,会发生以下事情:
next month
将月份数(原为 1)加 1.这使得日期为 2010-02-31.first day of
将天数设置为1
,从而得到日期 2010-02-01.
I've been working a lot with the DateTime class
and recently ran into what I thought was a bug when adding months. After a bit of research, it appears that it wasn't a bug, but instead working as intended. According to the documentation found here:
<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "
";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "
";
?>
Can anyone justify why this isn't considered a bug?
Furthermore does anyone have any elegant solutions to correct the issue and make it so +1 month will work as expected instead of as intended?
Why it's not a bug:
The current behavior is correct. The following happens internally:
+1 month
increases the month number (originally 1) by one. This makes the date2010-02-31
.The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.
How to get what you want:
To get what you want is by: manually checking the next month. Then add the number of days next month has.
I hope you can yourself code this. I am just giving what-to-do.
PHP 5.3 way:
To obtain the correct behavior, you can use one of the PHP 5.3's new functionality that introduces the relative time stanza first day of
. This stanza can be used in combination with next month
, fifth month
or +8 months
to go to the first day of the specified month. Instead of +1 month
from what you're doing, you can use this code to get the first day of next month like this:
<?php
$d = new DateTime( '2010-01-31' );
$d->modify( 'first day of next month' );
echo $d->format( 'F' ), "
";
?>
This script will correctly output February
. The following things happen when PHP processes this first day of next month
stanza:
next month
increases the month number (originally 1) by one. This makes the date 2010-02-31.first day of
sets the day number to1
, resulting in the date 2010-02-01.
这篇关于PHP DateTime::修改加减月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!