skip to Main Content

At 2022-09-30 i encountered weird behaviour of DateTime::createFromFormat, for pattern ‘Y-m’ and date ‘2022-02’ it returns 2022-03-02, now i know this is happening cause php will populate missing date values.

But today i wanna write some test cases with pattern !Y-m or Y-m| but i cant reproduce the error because now is 2022-10-03 so $d->createFromFormat('Y-m', '2022-02'); will not overflow to march, so can i somehow force DateTime::createFromFormat to return value as if it was launched on 2022-09-30 ?

I also tried creating new instance of DateTime and call createFromFormat on it, instead of static call:

$d1 = new DateTime('2022-09-30');
$d2 = $d1->createFromFormat('Y-m', '2022-02');
print_r($d2->format('Y-m-d')); // returns 2022-02-03, expected 2022-03-02

Also i am using php 7.4

2

Answers


  1. The definition of createFromFormat (https://www.php.net/manual/en/datetime.createfromformat.php) says that the arguments are in reverse order.

    Login or Signup to reply.
  2. Parsing an incomplete date and defining the missing components user-specifically is possible with the class Dt.

    $dateFragment = '2022-02';
    $dateInit = '2000-01-15 04:30';
    $regEx = '/^(?<Y>d{4})-(?<m>d{1,2})$/'; //4 digit year, hyphen, 1-2 digit month
    $timeZone = "Europe/Berlin";
    
    $date = Dt::createFromRegExFormat($regEx,$dateFragment,$timeZone,$dateInit);
    echo $date->format('Y-m-d H:i');  //2022-02-15 04:30
    

    The dateFragment returns only the month and year. A regular expression defines how the fragment is to be interpreted. Regular expressions are far more powerful than normal formatting. The missing information (day, hour, minute) is taken from dateInit.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search