why timezone_name_from_abbr fetching wrong result?
-
21-12-2019 - |
Вопрос
I face weird problem on converting offset to timezone name.
I use follwing code to convert offset to timezone.
$timezoneOffset = "+05:30";
echo $timezone_name = timezone_name_from_abbr("",$timezoneOffset*3600,0);
output: Asia/Karachi
Expected output: Asia/Kolkata
To check offset i use
$timezone = 'Asia/Kolkata';
$time = new \DateTime('now', new DateTimeZone($timezone));
$timezoneOffset = $time->format('P'); //output: +05:30
$timezone_name = timezone_name_from_abbr("",$timezoneOffset*3600,0);
echo $timezone_name;exit;
still the output is Asia/Karachi
So what is the problem? what should i do to solve this problem?
Thanks in advance.
Решение
Your calculation of the $gmtOffset
parameter (Offset from GMT in seconds) is incorrect.
In PHP, "+05:30" * 3600
gives 18000
as the result. This is because the string is converted to the integer 5
and then multiplied. This of course means that you're calling timezone_name_from_abbr()
with an offset of 300
minutes rather than your expected 330
minutes, leading to the "wrong" timezone name being returned.
If you wish to keep your existing $timezoneOffset
string, the following can be used to convert to the timezone offset in seconds.
$timezoneOffset = "+05:30";
$offsetSeconds = DateTime::createFromFormat('P', $timezoneOffset)->format('Z');