I use this function throughout my code. Pass it a date-like string or a DateTime(Immutable) object; it will spit out a PHP DateTime or DateTimeImmutable object, or false if input is a "0000-00-00"-like string. With the second parameter it can also force the result to be immutable or not:
function ensureDateTime ( $input, $immutable = NULL ) {
if ( ! $input instanceof \DateTimeInterface ) {
if ( in_array( $input, ['0000-00-00', '0000-00-00 00:00:00'], true ) ) {
$input = false;
} elseif ( $immutable ) {
$input = new \DateTimeImmutable( $input );
} else {
$input = new \DateTime( $input );
}
} elseif ( true === $immutable && $input instanceof \DateTime ) {
$input = new \DateTimeImmutable( $input->format(TIMESTAMPFORMAT), $input->getTimezone() );
} elseif ( false === $immutable && $input instanceof \DateTimeImmutable ) {
$input = new \DateTime( $input->format(TIMESTAMPFORMAT), $input->getTimezone() );
}
return $input;
}
Basically a "I'm not sure what I started with, but I know what I want", function.
(Note: A bit of PHP 7 syntax here, but easily adapted to PHP 5)