DEV Community

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

Posted on

2 2

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️