问题
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
Also, I restarted my PHP service after changing the timezone in php.ini
file.
I'm using XAMPP as a server.
Please note: the only correct time is by using pure php function!
Anyone can help me in resolving this issue?
回答1:
The time is correct: Z
at the end of the string means GMT
(Zulu timezone).
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.
If you try:
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.
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.
I explained it more in details here: https://medium.com/@kylekatarnls/always-use-utc-dates-and-times-8a8200ca3164
来源:https://stackoverflow.com/questions/62099032/laravel-carbon-returns-incorrect-time