Multiple Usages Of Date Default Timezone Set In Laravel

Viewed 32

I inherited a project written in PHP/ Laravel that uses the following way to get a time relative to a users timezone.

date_default_timezone_set($user->timezone);
$hour = date("H")
date_default_timezone_set('UTC');

Since this sets the default time zone for all of php, it seems that this could lead to issues with code running with the wrong users timezone if two instances of this code run very close together.

Does this have the potential to affect other code like im thinking it does?

Is there a better way to do this or is this even bad to begin with?

1 Answers

I would recommend using Carbon for dates.

Then you can create dates based on the user's timezone like so:

Carbon::now()
  ->tz($user->timezone);

The great thing is that the timezone is only set for that date, so it doesn't mess with your other PHP code.

Related