Laravel 5.3 - Carbon Date - UTC offset get timezone name

15,549

Solution 1

Tried updating Carbon to no evail ended up using the old datetime class.

$timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone));
$timezone = $dateTime->format('T');

Solution 2

Preface:

The accepted answer works in most cases but as mentioned in the user contributed notes area of timezone_name_from_abbr(), there are issues with using the function, like returning false instead of actual timezone and returning a "historical" (i.e. deprecated) timezone identifier rather than the current standard one for a given location. Which are still valid to this date.

Also, the original code returns the value as expected, as long as you know that as per Carbon docs, if you look at https://carbon.nesbot.com/docs/#api-timezone

the original name of the timezone (can be region name or offset string):

One more thing to note here is that, it is considered not reliable to derive timezone off of offset value as it does not take into consideration the DST observed periods offset.

So, this all to actually say that deriving timezone off of offset is not always possible.

Answer:

But since the OP mentioned Carbon and timezone based on offset, as per the Carbon docs as of now, the answer should be

$date = Carbon::now('-5');
echo $date->tzName;

Solution 3

In a new Carbon it is timezoneName property;

$now = Carbon::now(-5);
echo $now->timezoneName;
//or 
echo $now->timezone->getName();
Share:
15,549
Colton Wagner
Author by

Colton Wagner

I am a 26 year old Software Developer with a Bachelors Degree in Computer Science. I normally use Stack Overflow for side projects when learning new languages. I also use Stack Overflow for very complex PHP, Laravel, Python and Django problems.

Updated on June 23, 2022

Comments

  • Colton Wagner
    Colton Wagner almost 2 years

    I am trying to get a timezone name from a UTC offset in Laravel 5.3 using Carbon. Code listed below any help would be much appreciated.

    /* current code iteration */
    $utcOffset = -5;
    $timezone = Carbon::now($utcOffset)->timezone->getName();
    echo $timezone;
    // Result: -05:00
    // Expected Result: EST
    
    /* tried code */
    $timezone = Carbon::now($utcOffset)->tzName;
    // Result: -05:00
    
    /* What I used prior to Carbon */
    $timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
    $dateTime = new DateTime();
    $dateTime->setTimeZone(new DateTimeZone($timezone));
    $timezone = $dateTime->format('T');'
    

    What am I missing? I feel daft..