PHP strtotime +1个月的行为 [英] PHP strtotime +1 month behaviour

查看:114
本文介绍了PHP strtotime +1个月的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道PHP函数的有害行为

I know about the unwanted behaviour of PHP's function

strtotime

strtotime

例如,当在日期中添加一个月(+1个月),例如:31.01.2011-> 2011年3月3日

For example, when adding a month (+1 month) to dates like: 31.01.2011 -> 03.03.2011

知道它不是正式的 PHP错误 ,解决方案背后有一些争论,但至少对我而言,这种行为在过去和现在都造成了很多时间上的浪费,我个人讨厌它.

I know it's not officially a PHP bug, and that this solution has some arguments behind it, but at least for me, this behavior has caused a lot waste of time (in the past and present) and I personally hate it.

我发现甚至更陌生的是,例如:

What I found even stranger is that for example in:

MySQL :DATE_ADD("2011-01-31",间隔1个月)返回2011-02-28 或

MySQL: DATE_ADD('2011-01-31', INTERVAL 1 MONTH) returns 2011-02-28 or

C#,其中新的DateTime(2011,01,31).AddMonths(1);将返回28.02.2011

C# where new DateTime(2011, 01, 31).AddMonths(1); will return 28.02.2011

wolframalpha.com 给出31.01.2013 + 1 month作为输入;将于2013年2月28日星期四返回

wolframalpha.com giving 31.01.2013 + 1 month as input; will return Thursday, February 28, 2013

在我看来,其他人已经找到了解决这个愚蠢问题的更合理的解决方案,我在PHP错误报告中看到了很多情况,如果我说我们要在一个月后见面,那将是今天现在"或类似的内容.答案是:如果下个月不存在31,请告诉我该月的最后一天,但请坚持到下个月.

It sees to me that others have found a more decent solution to the stupid question that I saw alot in PHP bug reports "what day will it be, if I say we meet in a month from now" or something like that. The answer is: if 31 does not exists in next month, get me the last day of that month, but please stick to next month.

我的问题是:是否有一个PHP函数(由某人编写)可以解决这个未被官方认可的bug?因为我不认为我是唯一一个在添加/减去月份时想要另一种行为的人.

So MY QUESTION IS: is there a PHP function (written by somebody) that resolves this not officially recognized bug? As I don't think I am the only one who wants another behavior when adding / subtracting months.

我对解决方案特别感兴趣,该解决方案不仅可以在本月底使用,而且可以完全替代strtotime.另外,还应处理strotime +n months的情况.

I am particulary interested in solutions what also work not just for the end of the month, but a complete replacement of strtotime. Also the case strotime +n months should be also dealt with.

祝您编程愉快!

推荐答案

以下是您可以使用的算法.它应该足够简单来实现自己.

Here's the algorithm you can use. It should be simple enough to implement yourself.

  • 在变量中具有原始日期和+1个月日期
  • 提取两个变量的月份部分
  • 如果差异大于1个月(或者原始日期是12月而另一个不是1月),则将后一个变量更改为下个月的最后一天.例如,您可以在date()中使用t来获取最后一天:date( 't.m.Y' )
  • Have the original date and the +1 month date in variables
  • Extract the month part of both variables
  • If the difference is greater than 1 month (or if the original is December and the other is not January) change the latter variable to the last day of the next month. You can use for example t in date() to get the last day: date( 't.m.Y' )

这篇关于PHP strtotime +1个月的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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