How can update Current Timezone in the main configuration?
config/app.php
'timezone' => 'America/New_York',
I'm trying to update my app.timezone
base on clientTimeZone Asia/Kolkata
$date = new DateTime();
$timeZone = $date->getTimezone();
echo $timeZone->getName().PHP_EOL;
$timezone_offset_minutes = 330;
$clientTimeZone = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
echo $clientTimeZone .PHP_EOL;
Session::put('clientTimeZone',$clientTimeZone);
config('app.timezone', $clientTimeZone);
$date = new DateTime();
$timeZone = $date->getTimezone();
echo $timeZone->getName() .PHP_EOL;
This is the result
America/New_York
Asia/Kolkata
America/New_York
I have a feeling that this
config('app.timezone', $clientTimeZone);
is not taking any effect
Solution 1:
DateTime class accept two args, the second one is ?DateTimeZone $timezone = null
. If it's omitted or null, the current timezone will be used.
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime('now', $timezone);
The Laravel's app.timezone
config doesn't affect directly to DateTime.
On bootstrapping Laravel app it set up timezone this way
date_default_timezone_set($config->get('app.timezone', 'UTC'));
To work with client timezone you may set up it globally during session
$timezone_offset_minutes = 330;
$clientTimeZone = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
date_default_timezone_set($clientTimeZone);
Remember it doesn't affect any other apps, i.e. mysql. Mysql still will use app.timezone
readed on application bootstrap.
I propose to pass client timezone to any methods, functions and use it this way
$timezone_offset_minutes = 330;
$clientTimeZone = timezone_name_from_abbr("", $timezone_offset_minutes*60, false);
$this->getClientDateTime(new DateTimeZone($clientTimeZone));
//...
public function getClientDateTime(DateTimeZone $dateTimeZone): string
{
return new DateTime('now', $dateTimeZone->format('Y-m-d H:i:s');
}