To convert Carbon timezone to UTC, local time, etc to other timezone in Laravel; Carbon has methods like setTimeZone(), shiftTimeZone(), and tz(), these will be used to change timezones with and without changing hours, dates, and times.
Here are some options to set new timezone with and without changing hours, dates, and times in laravel:
Option 1: To set a new timezone without changing hours
To set new timezone using carbon without changing hours in laravel, simply use the setTimezone
function on a Carbon instance; as follows:
$today = Carbon::now(); // current timezone echo $today->timezone; // Asia/Tokyo //Change timezone without changing the hour $today->setTimezone('Asia/Dubai'); // new timezone echo $today->timezone; // Asia/Dubai
Option 2: Carbon Set Timezone Without Changing Time
To set timezone without changing time using carbon, simply use Carbon::now()
instance with shiftTimezone('Asia/Tokyo')
function to change it; as follows:
$today = Carbon::now(); // current timezone echo $today->timezone; // Asia/Tokyo //Change timezone without changing the time $today->shiftTimezone('Asia/Dubai'); // new timezone echo $today->timezone; // Asia/Dubai
Option 3: Convert Carbon dates and times between different timezones
To convert a Carbon object to a different timezone, simply use Carbon::now()
instance with tz('Asia/Tokyo')
function to change it; as follows:
$today = Carbon::now(); // current timezone echo $today->timezone; // Asia/Tokyo //Change timezone without changing the dates and times $today->tz('Asia/Dubai'); // new timezone echo $today->timezone; // Asia/Dubai
Here are some timezones supported by carbon Laravel that you can use in your Laravel configuration file:
'timezone' => 'Europe/Paris': Paris, France 'timezone' => 'America/New_York': New York, USA 'timezone' => 'Asia/Tokyo': Tokyo, Japan 'timezone' => 'Australia/Sydney': Sydney, Australia 'timezone' => 'Africa/Johannesburg': Johannesburg, South Africa 'timezone' => 'America/Sao_Paulo': São Paulo, Brazil 'timezone' => 'Asia/Dubai': Dubai, United Arab Emirates 'timezone' => 'Pacific/Auckland': Auckland, New Zealand 'timezone' => 'America/Mexico_City': Mexico City, Mexico 'timezone' => 'Europe/Moscow': Moscow, Russia
Conclusion
That’s it; In this tutorial, you learned how to set or change the timezone with and without changing hours, dates, and times by the setTimeZone(), shiftTimeZone(), and tiz() functions.
Reference docs: https://carbon.nesbot.com/docs/.