PHP DateTime :: modify添加和减去月份 [英] PHP DateTime::modify adding and subtracting months

查看:129
本文介绍了PHP DateTime :: modify添加和减去月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 DateTime类 ,最近遇到了我在添加月份时所想到的错误。经过一番研究,似乎这不是一个bug,而是按照预期的方式工作。根据此处的文档:

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:


示例#2添加时请小心或
减去月份

Example #2 Beware when adding or subtracting months



<?php
$date = new DateTime('2000-12-31');

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>




The above example will output:
2001-01-31
2001-03-03


任何人都可以证明为什么这不被认为是错误?

Can anyone justify why this isn't considered a bug?

此外,任何人都有任何优雅的解决方案来纠正问题,使其成为+1

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. +1个月增加月份数(原来是1)一个。这使得日期 2010-02-31

  1. +1 month increases the month number (originally 1) by one. This makes the date 2010-02-31.

第二个月(二月)只有28 2010年的日子,所以PHP自动纠正这一点,只是继续计算从2月1日起的日子。你将在3月3日结束。

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的新功能之一介绍相对时间段 的第一天。本节可以与下个月第五个月 +8个月去指定月份的第一天。您可以使用此代码来获取下个月的第一天,而不是 +1个月

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' ), "\n";
?>

此脚本将正确输出 February 。以下事情发生在PHP处理这个下个月的第一天节:

This script will correctly output February. The following things happen when PHP processes this first day of next month stanza:


  1. 下个月将月份号(原来是1)增加一个。这使日期为2010-02-31。

  1. next month increases the month number (originally 1) by one. This makes the date 2010-02-31.

的第一天将日期数设置为 1 ,导致日期为2010-02-01。

first day of sets the day number to 1, resulting in the date 2010-02-01.

这篇关于PHP DateTime :: modify添加和减去月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆