DEV Community

Cover image for How I created a PHP function to transform a Local DateTime to UTC
mattiatoselli
mattiatoselli

Posted on

How I created a PHP function to transform a Local DateTime to UTC

Today I had to resolve a problem at work, at first sight it could be simple, but hands on, it was not so.

Probably You will find another solution, but to me this was simple to code and enough easy to maintain. The idea is to use the functions that starting from PHP 5.4 we have to solve this problem.

I had an API which received the DateTime and the timezone, and I had to transform it in UTC before sending it to the DB, using Unix timestamp was not an option.

<?php
//we can specify GMT or for example a timezone name, under the snippet I'll provide the link to de documentation to find the names of the different timezones

$userTimezone = new DateTimeZone('GMT+2');

$myDateTime = new DateTime('2021-08-31 10:48', $userTimezone);

//get the offset of the selected timezone from UTC
$offset = $userTimezone->getOffset($myDateTime);

//create the corresponding DateTime in UTC
$myInterval=DateInterval::createFromDateString((string)$offset . 'seconds');
$myDateTime->sub($myInterval);

//print the result
$result = $myDateTime->format('Y-m-d H:i:s');
Echo $result;

Enter fullscreen mode Exit fullscreen mode

Usefull links

I have to mention this article which helped me very much, my snippet is an adaptation of this one here.

Also, for a better implemantation, i suggest to use the strings accepted by the method, you can consult the list in the PHP DOC here

Top comments (0)