使用DateInterval和DateTime :: add添加月份时可能会出错? [英] What can go wrong when adding months with a DateInterval and DateTime::add?

查看:138
本文介绍了使用DateInterval和DateTime :: add添加月份时可能会出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我未能找到适合此问题的解决方案。如您在PHP文档中的示例#3所示,他们指出,使用DateTime :: Add中的DateInterval



没有任何解释为什么方法的行为是这样的,我可以做什么来避免这一点,我发现这是一个

解决方案



p>问题是每个月可能有不同的天数。问题是当您要将日期增加1个月时,您正在做什么。根据PHP文档,如果您在1月31日(或30日),并且添加1个月,预期的行为是什么?



二月只有29天。你想要设置在这个月的最后一天吗?如果这是您要查找的内容,或者基于当前日期的静态日期,通常会更安全地增加一天。不知道你在增加月份时要完成什么,很难说如何观看错误。



编辑:

正如有人在上面的Mike B发表的类似帖子中提到的,你可能想要做一些你伪装的东西:

  1)在下个月使用cal_days_in_month()并将该数字保存到变量x 
2)如果x> =当前计费DOB,则增加并完成
3)DateTime :: modify('last天')(以前没有使用过这些,但是沿着这些行),将日期设置为下个月的最后一个日期(设置为下个月的第一天,然后是最后一天?)

I failed to find a proper solution to this issue. As you see in Example #3 in the PHP documentation, they state that one must beware when adding months using the DateInterval in DateTime::add.

There's not really any explanation for why the method's behavior is as such and what I can do to avoid this, which I find to be an error at first sight.

Anyone have some insight into this?

解决方案

The issue is that each month can have a different number of days in them. The question is what you're doing when you want to increment a date by 1 month. Per the PHP documentation if you're on January 31st (or 30th) and you add 1 month, what is the expected behavior?

February only has 29 days in it. Do you want to be set to the last day of the month? You're generally safer incrementing by a set number of days if that's what you're looking for, or a static date based on the current date. Without knowing what you're trying to accomplish when you increment your month, it's tough to say how to watch for an error.

EDIT:
As someone mentions in the similar post commented by Mike B above, you probably want to do something where you (in pseudocode):

 1) Use cal_days_in_month() for the next month and save that number to a variable x
 2) If x >= current billing DOB, increment and be done
 3) DateTime::modify('last day')  (havent used this before but something along these lines) to set the date to the last date of the next month (set it to the 1st of the next month, then last day?)

Worth noting is that if you use the variable here as the new billing value, you'll wipe out your original value. I would save an extra DB value that's "first billing date" or just "billing_day_of_month" or something, and use that to figure out the day of month that you should be looking at

这篇关于使用DateInterval和DateTime :: add添加月份时可能会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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