2

I try do date_diff last month, but have a problem if month have 31 day he say I'm to 01 at this month. And if do 2 month later give good result. But again every month who have 31 days give result to 01.

To be more clear i example you:

{{ "now" | date("Y-m-d") }} {# 2015-07-31 #}
{{ "now" | date_modify("-1 month") | date("Y-m-d") }} {# 2015-07-01 #}
{{ "now" | date_modify("-2 month") | date("Y-m-d") }} {# 2015-05-31 #}
{{ "now" | date_modify("-3 month") | date("Y-m-d") }} {# 2015-05-01 #}

Any1 have any ideea why ? Because any if modify month with even number you go at month start not to the end of previous month.

Laurentiu
  • 574
  • 6
  • 26
  • That seems bizarre - I assume that `\DateTime()` is being used under the hood. I tried the following in straight PHP (v 5.6) which replicates the issue: `$dt = new DateTime(); echo $dt->modify('-1 month')->format('Y-m-d');`. Going back two months yielded `2015-05-31`. Ah datetimes... Pretty interesting! – Darragh Enright Jul 31 '15 at 11:37
  • Hmm... check Example #2 in the [docs](http://php.net/manual/en/datetime.modify.php) - it says "Beware when adding or subtracting months", but it does not say why... – Darragh Enright Jul 31 '15 at 11:40
  • possible duplicate of [PHP DateTime::modify adding and subtracting months](http://stackoverflow.com/questions/3602405/php-datetimemodify-adding-and-subtracting-months) – Darragh Enright Jul 31 '15 at 11:53

1 Answers1

2

Based on the answer here it seems that when PHP modifies a DateTime() object with the string '-1 month' it simply decrements the month value, if I understand correctly.

So given your example, you start with today's date: 2015-07-31.

PHP changes this to 2015-06-31. However, there are only 30 days in June. So it increments this up to the next date that makes sense, which is... 2015-07-01.

I tried replicating this with:

echo (new DateTime())->sub(new DateInterval('P1M'))->format('Y-m-d');

and:

$dt = new DateTime();
$dt->modify('-1 month');
echo $dt->format('Y-m-d');

and I got the exact same result in each case:

2015-07-01

So I guess it's just one of PHP's foibles. Pretty messy, a lot can happen in a day!

Community
  • 1
  • 1
Darragh Enright
  • 13,676
  • 7
  • 41
  • 48