I really cannot understand why I get this error. I have 4 objects
<?php echo $_GET["allocDatesSt"]; ?> // "01/01/2023"
<?php echo $_GET["allocDatesEn"]; ?> // "08/01/2023"
<?php echo $_GET["reqDatesSt"]; ?> // "15/01/2023"
<?php echo $_GET["reqDatesEn"]; ?> // "22/01/2023"
All exactly the object type 'string'.
However when I use
<?php echo date_format(date_create($_GET["allocDatesSt"]), "d/m/Y"); ?>
<?php echo date_format(date_create($_GET["allocDatesEn"]), "d/m/Y"); ?>
<?php echo date_format(date_create($_GET["reqDatesSt"]), "d/m/Y"); ?>
<?php echo date_format(date_create($_GET["reqDatesEn"]), "d/m/Y"); ?>
The last two throw error
Fatal error: Uncaught TypeError: date_format(): Argument #1 ($object) must be of type DateTimeInterface ...
I just cannot understand why the first 2 work but the last 2 throws an error. What is the difference that I am missing?
CodePudding user response:
date_create only recognizes the format m/d/Y and not d/m/Y. If the month is > 12 then an error occurs. bool(false) is not a DateTime object and has no format method.
var_dump(date_create("08/01/2023"));
//object(DateTime)#2 (3) { ["date"]=> string(26) "2023-08-01 00:00:00.000000"
var_dump(date_create("15/01/2023"));
// bool(false)
Solution: Use DateTime::createFromFormat or date_create_from_format.
$_GET["reqDatesSt"] = "15/01/2023"; //Use assignments to $_GET for testing purposes only
echo date_format(date_create_from_format("d/m/Y",$_GET["reqDatesSt"]), "d/m/Y");
//15/01/2023