Get Current Date/Time in UTC Using DateTime
Class
To get the current time in UTC with the DateTime
class, we can simply specify the UTC time zone with an instance of DateTimeZone
like so:
$utcDateTime = new DateTime('now', new DateTimeZone('UTC')); echo $utcDateTime->format('Y-m-d H:i:s'); // output: '2020-12-31 22:28:21'
Convert Existing Date/Time Into UTC Using DateTime
Class
To convert the time zone to UTC of an existing DateTime
class instance, we can do the following:
$utcDateTime->setTimezone(new DateTimeZone('UTC')); echo $utcDateTime->format('Y-m-d H:i:s'); // output: '2020-12-31 22:28:21'
If the existing date/time is not already an instance of DateTime
class, then we can convert it in the following ways:
$utcDateTime = new DateTime($existingDateTime, new DateTimeZone('UTC')); echo $utcDateTime->format('Y-m-d H:i:s'); // output: '2020-12-31 22:28:21'
If the existing date/time has a custom format (which the DateTime
object cannot automatically convert or recognize), then you can specify the date/time format in the following way and convert it to the DateTime
object:
$existingDateTime = date('Y m d H-i-s'); $utcDateTime = DateTime::createFromFormat( 'Y m d H-i-s', $existingDateTime, new DateTimeZone('America/New_York') ); $utcDateTime->setTimezone(new DateTimeZone('UTC')); echo $utcDateTime->format('Y-m-d H:i:s'); // output: '2020-12-31 22:28:21'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.