Laravel Carbon返回错误的时间 [英] Laravel Carbon returns incorrect time
问题描述
我正在开发的Laravel应用存在问题,返回时间不正确,我确实在 config/app.php
和 php.ini <都指定了时区/code>文件,并使用以下命令清除了Laravel上的缓存:
I have an issue with my Laravel app that I'm developing, the returns time is incorrect, I did specify the timezone on both config/app.php
and php.ini
file, and I did clear the cache on Laravel using the following commands:
php artisan cache:clear
php artisan view:clear
php artisan config:cache
此外,在更改 php.ini
文件中的时区后,我重新启动了PHP服务.我正在使用XAMPP作为服务器.
Also, I restarted my PHP service after changing the timezone in php.ini
file.
I'm using XAMPP as a server.
请注意:唯一正确的时间是使用纯PHP函数!
任何人都可以帮助我解决这个问题吗?
Anyone can help me in resolving this issue?
推荐答案
时间正确:字符串末尾的 Z
表示 GMT
(祖鲁时区).
The time is correct: Z
at the end of the string means GMT
(Zulu timezone).
当Carbon实例在JSON响应中输出时,它总是在ISO-8601字符串中转换并在GMT时区给出,因为这是在系统之间交换日期信息的标准且非常推荐的方式(在JSON API中也是如此)).如果您尝试在浏览器中传递 new Date('2020-08-20T06:46:34.407Z')
,您将看到浏览器自动将其转换为用户时区.
When a Carbon instance is output in a JSON response, it's always converted in the ISO-8601 string and given in GMT timezone, as it's the standard and very recommended way to exchange date information between systems (and so in a JSON API). If you try to pass new Date('2020-08-20T06:46:34.407Z')
in a browser, you will see that it's automatically converted by the browser into the user timezone.
如果您尝试:
Carbon::now()->format('Y-m-d H:i:s.u')
您将看到它使用您选择的时区.您还可以将其显示在输出中:
You will see it uses the timezone you chose. And you also make it appear in the output:
Carbon::now()->format('Y-m-d H:i:s.u e')
因此处于不同时区的系统/浏览器不会使它混乱.
So a system/browser in a different timezone won't mess it up.
最好的办法仍然是在服务器端使用UTC,并且只在您想在该时区中显示特定用户的日期的最后一刻才使用Asia/Riyadh.
Still the best move is to work with UTC on your server side and only use the Asia/Riyadh at the very last moment when you want to display the date on a particular user you know is in this timezone.
我在这里进行了详细说明: https://medium.com/@kylekatarnls/always-use-utc-dates-and-times-8a8200ca3164
I explained it more in details here: https://medium.com/@kylekatarnls/always-use-utc-dates-and-times-8a8200ca3164
这篇关于Laravel Carbon返回错误的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!