How to set Laravel Carbon timezone for timestamps?

对着背影说爱祢 提交于 2020-01-12 14:13:49

问题


I have a project which is primarily based in CET region. I set CET in config/app.php, but all pivot timestamps in the base are stored in UTC time?

How can I set "global" timezone for timestamps?

i made this test:

<?php
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;
echo "<br />".date('m/d/Y h:i:s a', time());

$mytime = Carbon\Carbon::now();
echo "<br />".$mytime->toDateTimeString();
?>

and here's the result:

The current server timezone is: CET
06/09/2016 12:06:04 pm
2016-06-09 11:06:04

tnx Y


回答1:


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




回答2:


in the AppServiceProvider.php you can add the php functionality to alter the timestamp for the whole project

public function boot()
{
    Schema::defaultStringLength(191);
    date_default_timezone_set('Asia/Aden');
}



回答3:


Update file config/app.php

Eg: 'timezone' => 'Asia/Jerusalem' instead of 'timezone' => 'UTC'




回答4:


You can achieve it with mutators

public function getCreatedAtAttribute($value)
{

return Carbon::createFromTimestamp(strtotime($value))
    ->timezone(Config::get('app.timezone'))
    ->toDateTimeString(); //remove this one if u want to return Carbon object
}



回答5:


It looks like solution is to use not "CET" but one of explicit timezones, for example: "Europe\Minsk"

PHP Timezones

Timezones in Laravel 4




回答6:


If you are using Laravel Carbon TimeStamps, then you have to change timezone in App/Providers/AppServiceProvider.php file

// App/Providers/AppServiceProvider.php

public function boot()
{
    date_default_timezone_set('Asia/Calcutta');
}


来源:https://stackoverflow.com/questions/37722681/how-to-set-laravel-carbon-timezone-for-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!