This content originally appeared on DEV Community and was authored by mattiatoselli
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;
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
This content originally appeared on DEV Community and was authored by mattiatoselli
mattiatoselli | Sciencx (2021-08-31T12:19:41+00:00) How I created a PHP function to transform a Local DateTime to UTC. Retrieved from https://www.scien.cx/2021/08/31/how-i-created-a-php-function-to-transform-a-local-datetime-to-utc/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.