phpdatetimepersianpersian-calendarjalali-calendar

PHP DateTime gives incorrect value


I wonder why this php code gives incorrect output value.

dd(new \DateTime("1397/02/29", new \DateTimeZone('Asia/Tehran')));

It outputs below object:

DateTime @-18076965944 {#1256 ▼
  date: 1397-03-01 00:00:00.0 Asia/Tehran (+03:25)
}

As you see the date is incorrect and must be 1397-02-01. The output for values 1397/02/30 && 1397/02/31 is incorrect also.

Can anyone help please. thanks.


Solution

  • PHP store date object internal as struct https://github.com/php/php-src/blob/master/ext/date/php_date.h#L137 https://github.com/php/php-src/blob/master/ext/date/lib/timelib.h#L204

    But DateTime init have no validating and only converts given date string to timestamp. https://github.com/php/php-src/blob/master/ext/date/php_date.c#L2647

    Before creating date object you should check it using http://php.net/manual/en/function.checkdate.php

    var_dump(
        checkdate(2,20,1000), // bool(true)
        checkdate(2,30,1000) // bool(false)
    );