'How to convert time from one timezone to another in PHP
I have a code see below. The time zone for the time 16:17
is Europe/Vilnius
. My goal is to apply time zone $tz2 = 'Africa/Dakar'
and get 16:17
time in Africa/Dakar
time zone.
$tz1 = 'Europe/Vilnius';
$tz2 = 'Africa/Dakar';
$a='16';
$b='17';
$match_time = date("H:i", strtotime($a.":".$b));
$dt1 = new DateTime($match_time, $tz1);
$dt2 = new DateTime($match_time, $tz2);
echo "match date".$match_time;
echo "dt1".$dt1;
echo "dt2".$dt2;
I tried many ways to do that. Right now this code gives me an error:
FATAL ERROR Uncaught Error: Call to a member function format() on string in /home4/phptest/public_html/code.php70(5) : eval()'d code:8 Stack trace: #0 /home4/phptest/public_html/code.php70(5): eval() #1 {main} thrown on line number 8
My question how to fix a code to get the result, and is this a convenient way to do such conversion?
Solution 1:[1]
date_default_timezone_set('Europe/London');
$datetime = new DateTime('2008-08-03 12:35:23');
echo $datetime->format('Y-m-d H:i:s') . "\n";
$la_time = new DateTimeZone('America/Los_Angeles');
$datetime->setTimezone($la_time);
echo $datetime->format('Y-m-d H:i:s');
Solution 2:[2]
The type of the argument is a DateTimeZone for the DateTime. You are passing a string.
You can do it like this:
$tz1 = 'Europe/Vilnius';
$tz2 = 'Africa/Dakar';
$a='16';
$b='17';
$match_time = date("H:i", strtotime($a.":".$b));
$dt1 = new DateTime($match_time, new DateTimeZone($tz1));
$dt2 = new DateTime($match_time, new DateTimeZone($tz2));
echo "match date".$match_time;
echo "dt1".$dt1->format('Y-m-d H:i:s');
echo "dt2".$dt2->format('Y-m-d H:i:s');
To echo the DateTime you can use format.
Solution 3:[3]
You can't just pass timezone as string in a second argument. You have to create new instance of DateTimeZone
class with timezone name as constructor parameter. For example:
<?php
$dt = new DateTime("16:17", new DateTimeZone('Europe/Warsaw'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ali Kaviani |
Solution 2 | The fourth bird |
Solution 3 | Wolen |