Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.3 - Carbon Date - UTC offset get timezone name

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..

like image 929
Colton Wagner Avatar asked Dec 24 '22 19:12

Colton Wagner


2 Answers

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;
like image 131
A.G. Avatar answered Dec 26 '22 09:12

A.G.


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');
like image 25
Colton Wagner Avatar answered Dec 26 '22 09:12

Colton Wagner