Home > Software engineering >  Should I keep Laravel UTC as Laravel Timezone?
Should I keep Laravel UTC as Laravel Timezone?

Time:12-02

Laravel documentation says :

... You are strongly encouraged to always use this serialization format, as well as to store your application's dates in the UTC timezone by not changing your application's timezone configuration option from its default UTC value. ...

I'm confused, how/when am I supposed to change the timezone of the dates ? I know that if I pass a UTC date to javascript it would be converted to the user's timezone (with new Date(), right ?) but what if I'm gonna show the data directly to the user without going through javasacript ? (like a blade page, generating a pdf ...), how can I make sure that the timezone will be the same across the application? I know Carbon can be used to convert dates timezone but I don't want to manually do the conversion everytime, should I like add a custom configuration variable or is there a better way to do it ?

CodePudding user response:

Timezone should be changed when:

  • To user timezone: when you present the date
  • To UTC: when you get the date from the user input

I personally use macros for this

Carbon::macro('toUTC', fn() => $this->setTimezone('UTC'));
Carbon::macro('toUserTimezone', fn(?User $user = null) => $this->setTimezone('Europe/Zurich'));

Then I use it like this

{{ $date->toUserTimezone()->isoFormat('LL') }}

A side note on this:

Some reasons why it's encouraged to use UTC,

I'm sure there's more to this, feel free to comment if you know any.

  • Related