Laravel Carbon返回时间异常问题求助
Hey there, let's work through this timezone issue you're facing—since pure PHP functions are working fine, the problem is likely specific to how Laravel is loading or overriding timezone settings. Here are targeted steps to diagnose and fix it:
Check for environment variable overrides
Laravel prioritizes values from your.envfile over theconfig/app.phpsettings. Open your.envfile and look for anAPP_TIMEZONEentry. If it exists and doesn't match your desired timezone (e.g.,Asia/Shanghai,America/New_York), update it and runphp artisan config:cacheagain to apply changes. If it doesn't exist, you can add it explicitly to ensure consistency.Verify Laravel's active timezone
Add a quick debug check in a test route or controller to confirm what timezone Laravel is actually using:Route::get('/check-timezone', function () { dd( 'Laravel config timezone: ' . config('app.timezone'), 'PHP default timezone: ' . date_default_timezone_get(), 'Current Carbon time: ' . Carbon\Carbon::now()->toDateTimeString() ); });Visit this route and compare the outputs. If
config('app.timezone')isn't what you set, it means your config cache wasn't properly cleared or there's a config override somewhere.Ensure you're modifying the correct php.ini files
XAMPP sometimes uses separate php.ini files for the web server (Apache) and CLI. Run these checks to confirm which files are being loaded:- For web: Create a
phpinfo.phpfile with<?php phpinfo(); ?>, access it via your browser, and look for "Loaded Configuration File". - For CLI: Open your terminal, navigate to your XAMPP php directory, and run
php -i | grep "Loaded Configuration File".
Make sure both files have the correctdate.timezonesetting, then restart Apache and your CLI session.
- For web: Create a
Check for hardcoded timezone overrides in your code
Search your project for instances where the timezone is manually set, like:Carbon\Carbon::setTimezone('UTC'); date_default_timezone_set('UTC');These hardcoded values will override your global config. Pay special attention to models, service classes, or middleware that might manipulate time settings.
Validate database timezone configuration
If your issue relates to timestamps stored in the database, check yourconfig/database.phpfile. For MySQL, ensure you have atimezoneentry in the mysql configuration array:'mysql' => [ // ... other settings 'timezone' => '+00:00', // or your desired timezone, e.g., '+08:00' for UTC+8 ],This ensures Laravel correctly converts database-stored times to your app's timezone.
After trying these steps, clear your Laravel cache again with:
php artisan cache:clear php artisan config:clear php artisan config:cache
内容的提问来源于stack exchange,提问作者Adel AlMajed

