繁体   English   中英

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它是timezoneName属性;

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

前言:

接受的答案在大多数情况下都有效,但正如timezone_name_from_abbr()的用户提供的注释区域中所提到的,使用该函数存在问题,例如返回false而不是实际时区并返回“历史”(即已弃用)时区标识符而不是给定位置的当前标准。 到目前为止仍然有效。

此外,原始代码会按预期返回值,只要您知道根据Carbon文档,如果您查看https://carbon.nesbot.com/docs/#api-timezone

时区的原始名称(可以是区域名称或偏移字符串):

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

所以,这实际上说,从偏移量中获取时区并不总是可行的。

回答:

但由于OP提到基于抵消的碳和时区,根据截至目前的Carbon文档,答案应该是

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

尝试使用旧的日期时间类更新碳到无恶意。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM