How carbon's timezone are working? How to get date time based on specified timezone?

Viewed 773

I'm struggling with the Carbon::now(), I'm specifying the desired timezone in the now function and it is not giving the date time based on the given timezone. It always using the UTC timezone that's specified in the laravel.

Carbon::now() // giving me date time of UTC timezone
Carbon::now('Asia/Karachi') // still giving me the date time of UTC timezone
var_dump(Carbon::now('Asia/Karachi')) // I'm able to see the correct date time based on the timezone. 

So when I use the var_dump() I'm getting the correct date time based on the give timezone. Can anyone explain why it is nog returning the correct timezone from the Carbon::now('Asia/Karachi')? but dumping the instance showing the correct datetime.

I've also tried the php artisan cache:clear as well as php artisan config:clear

2 Answers

In config/app.php file change UTC to your desired timezone. It will change app timezone globally. Eg: 'timezone' => 'Asia/Dhaka',

It always using the UTC timezone

Where? If you're talking about a JSON output, it's expected, date is formatted with ISO-8601 string and a trailing Z meaning Zulu = GMT timezone. The browser or client reading this JSON will have no issue to reconvert it then to any local date time using the user device timezone.

But at anytime if you dump explicitly this instance to a string using any format, the specified timezone will be used:

Carbon::now('Asia/Karachi')->format('Y-m-d H:i:s.u p')

(here using p or e you will see explicitly the timezone in the string.

Related