This is a rather simple question, but I couldn't really find an answer on the Internet.
So suppose, in PHP, I have an instance of a DateTimeInterface, and I need a DateTime for the same moment in time. What is the preferred way to do so? Conversion via a string seems rather convoluted, and I'm not sure which format to use. Maybe via the timestamp? I'm not sure if this will work when timezones are involved.
In PHP 8: createFromInterface:
$dateTime = DateTime::createFromInterface($dateTimeInterface);
In you are in PHP 7 (and maybe even earlier), this little helper class can do the trick for you:
class DateTimeConverter
{
public static function mutableFromInterface(\DateTimeInterface $dateTimeInterface): \DateTime
{
return new \DateTime('@'.$dateTimeInterface->getTimestamp(), $dateTimeInterface->getTimezone());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With