How can I catch '02/31/2010' as an invalid date using the DateTime class?

I use the DateTime class in PHP because date () has a minus Unix timestamp. However, none of the approaches finds incorrect dates for months that do not have 31 days, but try to use the 31st day.

Code example:

try {
$date = new DateTime('02/31/2018');
$formattedDate = $date->format('Y-m-d');
} catch (Exception $e) {}
echo $formattedDate;

Result:

2018-03-03

Update 1: To use checkdate (), I need the date parts. To do this, I need to instantiate a DateTime object with a date string as a constructor. In the case of '02 / 31/2018 'he will convert it to '03 / 03/2018' when creating the instance. At this point, it will be too late to start the component month, day, year through checkdate (). What is the solution?

2: , (, mm/dd/yyyy), , strtotime(), checkdate strtotime() β†’ date() DateTime:: __ construct β†’ DateTime:: format().

+3
3

, ...

$date = explode('/','02/18/2018');

checkdate(), .

0

checkdate.

. , .

1 12 .

. .

1 32767 .

+6

Extend DateTime and recreate the default constructor to use checkdate . A bit is easier to do this once and replace all DateTime ( with MyDateTime ( ) so that you can add additional checks as you move. For example, Year> 1940 ...

+2
source

Source: https://habr.com/ru/post/1710503/


All Articles