Dylan
Dylan

Reputation: 5

How to return timestamp based on user timezone?

Say that I have a timezone variable which is returned from a database that my users can set to their prefered time zone. GMT+5 would return simply as:

$timezone = 5;

I need the users timezone so that I can reflect the date of an event in their particular time format. Here is what I have so far:

while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time = strftime("%Y-%m-%d %I:%M %p", strtotime($row["time"]));
}
echo $time;

How could I change the above output to reflect the time of the event based on the users preferred time zone?

//Output = 2017-01-15 12:09 AM 
//Expected Output: 2017-01-14 07:09 PM  

Upvotes: 0

Views: 99

Answers (1)

Boris Guéry
Boris Guéry

Reputation: 47585

Use the DateTime and DateTimeZone objects.

<?php

$storedDate = new DateTime('2017-01-15 12:09 AM');
$userDate   = (clone $storedDate)->setTimeZone(new DateTimeZone('Europe/Paris'));

printf(
    "Stored Date:\t%s\nUser Date:\t%s\n",
    $storedDate->format(DATE_ATOM),
    $userDate->format(DATE_ATOM)
);

// outputs:
// Stored Date:    2017-01-15T00:09:00+00:00                                                                               
// User Date:      2017-01-15T01:09:00+01:00

As said in my comment, I dot not advise to store the timezone as an integer.

First, because some timezone can't fit an integer, for example India is up to 5:30 (+0530) from the UTC time.

Storing as integer also won't help you to properly handle summer time in some countries, or even in some region in a same country (see Brazil).

Timezone offset are subject to change, but defined configuration for a given location such as Europe/Paris are likely not.

Upvotes: 1

Related Questions