Laravel 5.3 - Carbon Date - UTC 偏移获取时区名称

Laravel 5.3 - Carbon Date - UTC offset get timezone name

我正在尝试使用 Carbon 从 Laravel 5.3 中的 UTC 偏移获取时区名称。下面列出的代码如有任何帮助,我们将不胜感激。

/* 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');'

我错过了什么?我觉得很蠢..

这对我有用:

$now = Carbon::now(-5);

echo $now->timezone;
// prints 'America/Chicago'

尝试更新 Carbon 无济于事,最终使用旧的日期时间 class。

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

在新的 Carbon 中是 timezoneName 属性;

$now = Carbon::now(-5);
echo $now->timezoneName;
//or 
echo $now->timezone->getName();

前言:

接受的答案在大多数情况下都有效,但正如 timezone_name_from_abbr(), there are issues with using the function, like returning false instead of actual timezone 的用户贡献的注释区域中所述,并返回 "historical"(即已弃用)时区标识符,而不是给定的当前标准时区标识符地点。至今仍有效。

此外,原始代码 returns 是预期的值,只要您知道按照 Carbon 文档,如果您查看 https://carbon.nesbot.com/docs/#api-timezone

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

这里还要注意的一件事是,从偏移值中推导出时区被认为是不可靠的,因为它没有考虑 DST 观测周期偏移。

所以,这实际上是说从偏移量导出时区并不总是可能的。

答案:

但是由于 OP 提到了基于偏移量的 Carbon 和时区,根据目前的 Carbon 文档,答案应该是

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