Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to understand behavior of the DateTime class in PHP

Tags:

php

datetime

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

like image 464
Sohel Ahmed Mesaniya Avatar asked Dec 09 '16 12:12

Sohel Ahmed Mesaniya


Video Answer


1 Answers

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)

like image 162
cb0 Avatar answered Oct 11 '22 09:10

cb0