new DateTime("@".$timestamp) should not crash (throws fatal error) with empty timestamp
Description
When creating a DateTime object with @ + timestamp (e.g. @123987139) the date is forced to UTC. That works fine.
Working Code:
$timestamp =123987139;
$date = new DateTime("@".$timestamp); // @ Forcing to UTC
However, if the timestamp is empty, php will throw an fatal error like "PHP Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (@) at position 0 (@): Unexpected character in ..."
Non-working Code:
unset($timestamp) ;
$date = new DateTime("@".$timestamp); // @ Forcing to UTC
Actual behaviour: Script throws fatal error, resulting in error 500, whole script stops
Desired behavior: Throwing just a warning or nothing, returned value should be 0 or false, script continues
Thanks for the report but I don't really understand why you think there should be no error. Luckily for you, the procedural API doesn't throw errors, so you can use that and check for errors manually.
<?php
$timestamp = null;
$date = date_create("@".$timestamp); // @ Forcing to UTC
This is not a but.
Similar illegal requests throw the same exception like for example new DateTime('null');. It is your responsibility as a developer to make sure that something sensible is passed to the constructor.
In addition: I would not use DateTime anymore but DateTimeImmutable to avoid weird errors (which then means that you can't use date_create)
I would recommend something like the following if you want to go down the rabgit hole of having DateTimeImmutable|false as possible value for $date. As that now forces you to check on every usage of $date whether that is actually a DateTimeImmutable object or not...
$date = false;
if ($timestamp >= 0) {
$date = new DateTimeImmutable('@' . $timestamp);
}
As a side-note: UTC is not "forced". A timestamp is by it's very own definition "the seconds passed since 1st of January 00:00:00 UTC". So a timestamp is always based on UTC and a DateTime(Immutable) object created from one can not have any other timezone than UTC.
Thanks for the suggestion! I'm sorry for the confusion, the code snippet incl. comment was taken out of context here, and I explained it wrong. At the point of the code it was meant like "using timestamp to force UTC date" (instead of a non-UTC date string).
First, there is no fatal error, but rather an Exception is thrown (https://3v4l.org/JCpa7). Not catching that exception results in a fatal error.
Second, a failing constructor must throw, because otherwise you would have an uninitialized object.
That sounds like you already got a DateTime object and you want to do something like $date->setTimeZone(new DateTimeZone('UTC'));? If not: Why not open a question on StackOverflow with the actual issue that you are trying to solve? And when you link to it from here others can find that then as well :wink: