Home > front end >  Strange behaviour of Carbon
Strange behaviour of Carbon

Time:08-10

I am working on a Laravel app and I am trying to convert some dates to a different timezone and format with the timezone in the string. Here is the code, I've got:

public static function convertDateToUserTimezone($date, $timezone = '', $format = 'Y-m-d H:i:s')
{
    $userTimezone = auth()->user()->timezone;
    $timeFormat = $format . $timezone;

    return (Carbon::createFromFormat($format, $date))->setTimezone($userTimezone)->format($timeFormat);
}

and I am calling this function in the following:

Class:convertDateToUserTimezone($date, 'ZZ');

for example for this datetime: 2022-08-09 22:39:36 I expect to get 2022-08-10 01:39:36 0300

as the default Laravel timezone is UTC and I am converting to Europe/Sofia but I get this: 2022-08-10 01:39:361080010800. Why is the timezone not in the format I requested?

I haven't used Carbon much so there is probably something I am missing.

Tried googling various things but nothing helped.

CodePudding user response:

The issue is your format is wrong. 'ZZ' calls the Z format character twice and that's not the format character you want.

Here's an extract of the possible formats. You can view the full table at https://www.php.net/manual/en/datetime.format.php

format character Description Example returned values
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: 0200
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: 02:00
p The same as P, but returns Z instead of 00:00 (available as of PHP 8.0.0) Example: 02:00
T Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST, MDT, 05
Z Timezone offset in seconds.The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 5040

ZZ is giving you 1080010800 (10800 twice.) This is consistent with the timezone you set. Europe/Sofia is GMT 3. 10800 seconds = 180 minutes = 3 hours.

Based on your function and this table, I'd say you want to call it like this:

Class:convertDateToUserTimezone($date, 'O');
  • Related