在 laravel 框架中,我尝试在 config 下面的配置文件中,使用 Carbon 获取时间,但是发现时区并不是在 app.timezone 中设置的时区。我还没有查看到原因。
自定义时区设置
如果要在配置文件中使用时区,可以按照以下方式
Carbon::now()->tz(config('app.timezone'))->format('Ymd H:i:s')
或者
Carbon::now(config('app.timezone'))->format('Ymd H:i:s')
- 查看 now() 方法,可以知道,其实很多的方法中都有 tz 参数,这个参数代表时区。但是默认是使用的默认时区。如果在使用时间的时候,发现时区不对,可以添加此参数,但是我指在 config 中使用时区发了问题
/**
* Get a Carbon instance for the current date and time.
*
* @param \DateTimeZone|string|null $tz
*
* @return static
*/
public static function now($tz = null);
- 中文时区是 PRC
语义化设置。注意,这个是显示时间的语言,跟上面的时区不一样
dump(Carbon::getLocale()); // "zh_CN"
dd(Carbon::parse('2019-08-01')->diffForHumans()); // "4周内"
- 也可以设置时区
Carbon::setLocale('zh');
- 时区语言可以在
App\Providers\AppServiceProvider
的 boot 方法中设置,这也是大家推荐的一种方式。但是你如果不在这里设置,是会读取app.locale
配置的。不过app.locale
这个配置其实也是针对于resources/lang/
文件的 Validate 报错使用的语言包。可能是为了不与这个配置造成冲突,才在boot
里面设置的吧。但是很多时候,我们是不需要时区的汉化的,我们只是计算时间。这种情况下,你就不需要费心思设置了
App\Providers\AppServiceProvider.php
public function boot()
{
\Carbon\Carbon::setLocale('zh');
}
// 优先使用此配置,没有则使用 app.locale
可用的时区语言版本.png
注意
经测试,在配置中使用 Carbon 还是有问题
\Carbon\Carbon::createFromTimeString('9:30:15')->timestamp , 打印会得到 "20190703 17:30:15"
但是
\Carbon\Carbon::createFromTimeString('9:30:15')->format('Y-m-d H:i:s') // 打印得到的就正常
即使
$startTime = Carbon::parse($startTime)->timestamp;
dd(date('Ymd H:i:s',$startTime));
也是正常的。所以,尽量不要在配置中使用 Carbon ,如果非要使用,则不要使用 timestamp 转换时间戳
网友评论