Laravel +碳+时区 [英] Laravel + Carbon + Timezone

查看:33
本文介绍了Laravel +碳+时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 config/app.php 中的时区配置为欧洲/里斯本.

I have configured the timezone in config/app.php to Europe/Lisbon.

如果我执行 return date_default_timezone_get(); ,它将按我的要求返回 Europe/Lisbon .

If I do a return date_default_timezone_get();, It returns Europe/Lisbon like I want.

到目前为止一切顺利!

当我执行 Carbon :: now()时,它返回例如16小时,而当前时间是17h.有人可以解释为什么不考虑夏令时吗?

When I do Carbon::now() it returns for example 16 hour while the current time is 17h. Can someone explain why the daylight saving aren't considered?

我正在使用Laravel 7.16,PHP 7.4

I'm using Laravel 7.16, PHP 7.4

致谢

代码图片+时间| https://imgur.com/pfh6uij

总是要做的 php artisanoptimize:clear 可以在我更改配置中的所有内容时清除所有缓存.

EDIT 2: always done php artisan optimize:clear to clear all caches when I change something in the config.

模型上的created_at和updated_at的时间正确了.

EDIT 3: created_at and updated_at on models are getting correct times.

return Carbon :: now()返回不良时间.进行 dd(Carbon :: now())返回正确的值,并在 config/app.php 中配置时区.dd()示例->日期:2020-07-08 17:25:28.935949欧洲/里斯本(+01:00)

EDIT 4: return Carbon::now() returns bad hours. Doing dd(Carbon::now()) returns the correct values, with the Timezone configured in config/app.php | dd() example -> date: 2020-07-08 17:25:28.935949 Europe/Lisbon (+01:00)

在github上打开了一个问题- https://github.com/laravel/framework/issues/33475

EDIT 5: Opened an issue at github - https://github.com/laravel/framework/issues/33475

就我而言,我使用php date()函数来解决此问题.不是我想要的方式,但能完成工作...

EDIT 6: In my case, I used the php date() function to workaround the problem. Not the way I wanted but does the job...

if (date(now()) > $subscriber->token_expire_date)
{
    // return not found response
    return $this->response(false, 410, 'The token has expired.', []);
}

推荐答案

Carbon使用默认的 DateTime PHP对象,因此请使用 date_default_timezone_set()函数,例如:date_default_timezone_set('欧洲/里斯本');

Carbon uses the default DateTime PHP object, so use the date_default_timezone_set() function, for example: date_default_timezone_set('Europe/Lisbon');

或定义它 AppServiceProvider App/Providers/AppServiceProvider.php

public function boot()
{
    date_default_timezone_set('Europe/Lisbon');
}

或者您可以使用碳方法的 setTimezone

Or you can use setTimezone of carbon method

echo Carbon::now()->setTimezone('Europe/Lisbon')->format('H:i');

这篇关于Laravel +碳+时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆