Vasileios Tsakalis
Vasileios Tsakalis

Reputation: 1211

PHP - Display data in different time zones

Hello stackoverflow community.

I develop a web app and the concept is to display historical currency exchange rates based on time series from past.

For example a user may request exchange rates from 22 May 2020 13:00 to 26 MAY 2020 22:00. Then my backend run a loop and get the rates between those two date times each hour.

All rates in database stored in GMT time zone.

And here is the problem. Let's suppose a user make a request from a time zone offset +10:00. So if this user pick as last date time 26 MAY 2020 22:00, I guess I should grab from my database the rate in 26 MAY 2020 12:00, so to subtract 10 hours.

May this sound stupid, but I'm stuck with this.

What is my logic:

a) Get the users time zone offset via javascript in front-end

var get_timezone_offset = new Date().getTimezoneOffset();

var hrs = parseInt(-(timezone_offset / 60));

var mins = Math.abs(timezone_offset % 60);

var timezone_offset = hrs + ':' + mins;

b) Send users time zone offset to my backend

c) Get rates from my database and convert date stored from GMT to users time zone offset via PHP's Datetime object

$date = new \DateTime('2020-05-26 22:00');

$date->modify(-10 hours);

$date->format('Y-m-d H:i:s');

Is this right? I won't display wrong rates to my users.

Thank you in advance

Upvotes: 2

Views: 844

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241525

Please read the timezone tag wiki, especially the section titled "Time Zone != Offset". In short, you cannot assume the offset taken now from the user is the same one that will apply at any other point in time.

A simple example is for time zones like America/New_York, which presently is UTC-4, but will switch to UTC-5 when daylight saving time ends in November. But besides DST, many time zones have had changes in their standard time offsets.

Instead of getting the current numeric offset, get the IANA time zone identifier from the browser.

const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
// example: "America/New_York", "Asia/Kolkata", "Europe/Athens", etc.

Then you can use this identifier with PHP's built-in time zone support. For example, the following converts from a local time in a given time zone to the equivalent time in UTC:

$tz = new DateTimeZone("America/New_York");
$date = new DateTime('2020-05-26 22:00', $tz);
$date->setTimeZone(new DateTimeZone("UTC"));
echo $date->format('Y-m-d H:i:s');

Upvotes: 2

Related Questions