Search code examples
laraveltimezonephp-carbon

Get offset hourse for local time from GMT time - Laravel Carbon


I am developing a laravel application which stores GMT time in database accross the world.

Now I want user to see time in his local timezone but for this I must aware of user's local timezone which I don't.

I have user's country ISO code and using DateTimeZone::listIdentifiers method I can get the timezone but it returns array of timezones for some countries.

So is there a method or way through which I can get offset in hours between GMT +00:00 and user's local GMT time?


Solution

  • You need to make some request passing the timezone from client/browser to your server to get an accurate timezone.

    Many countries have multiple timezones, Russia, USA, just to mention some. So country code is not enough.

    Then, don't use offset, use named timezone as many timezones also have multiple offset due to daylight saving. Europe/Paris can be GMT+1 or GMT+2 and so current offset between GMT+0 now != current offset for your given timestamp.

    When you have the precise city name of the timezone, then it's really simple to use it before formatting a Carbon date:

    Carbon::createFromTimestamp($utcTimestamp)->tz('America/New_York')