5

I am using LAMP in Kubuntu 14.04 with PHP 5.6.23.

When using DateTime in follwing cases:

1.

print_r((new DateTime('2016-02-31'))->format('M/d/Y')); 
// Mar/02/2016 (no errors, why?)

2.

print_r((new DateTime('2016-02-32'))->format('M/d/Y')); 
// Error - DateTime::__construct(): Failed to parse time string-
// (2016-02-32) at position 9 (2): Unexpected character

Why the first case give me no error, as there is no 31st date of February month?

References supporting answer are requested

Dave
  • 3,073
  • 7
  • 20
  • 33
Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
  • 2
    have you ever seen a month with more than `31` days ? – Blueblazer172 Dec 09 '16 at 12:52
  • The error comes because there are no months with more than 31 days. It works for February because it adds the extra days (2 or 3) and results in March. See this answer: http://stackoverflow.com/questions/3602405/php-datetimemodify-adding-and-subtracting-months#answer-3602421 – Musterknabe Dec 09 '16 at 12:53
  • Because `32` is not a legal day of the month. The other case it will notice that there is no 31 of feb and will calculate the correct next day. – cb0 Dec 09 '16 at 12:53

1 Answers1

7

From the php docs:

It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

Note that as of PHP 5.1.0 the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.

This makes it pretty clear.

In the user notes Mirek also suggest to use mktime if you need:

unlimited over/underflow for date calculations (for example 2015-01-40 to 2015-02-09)

cb0
  • 8,415
  • 9
  • 52
  • 80