Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a DateTime from a DateTimeInterface in PHP?

Tags:

php

datetime

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.

like image 706
johanv Avatar asked May 23 '26 13:05

johanv


2 Answers

In PHP 8: createFromInterface:

$dateTime = DateTime::createFromInterface($dateTimeInterface);
like image 66
JW. Avatar answered May 25 '26 06:05

JW.


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());
    }
}
like image 36
magnetik Avatar answered May 25 '26 08:05

magnetik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!