So I have a site with a comments feature where the timestamp of the comment is stored in a MySQL database. From what I understand, the timestamp is converted to UTC when stored, then converted back to the default timezone when retrieved. In my case, my server is in the Central Daylight Time timezone (CDT).
I have a plan to get the timezone from each user via entry form. I just wanted to know how to convert the TIMESTAMP value into the user's timezone.
- First, would I convert from UTC to local timezone? Or CDT to local timezone?
- Secondly, how would I go about doing that in PHP? Would I just do:
$userTimezone = new DateTimeZone($userSubmittedTimezoneString); $myDateTime = new DateTime($storedTimestamp, $userTimezone);
...or is that not correct?
The way to do it is by using javascript. I think the best way to do it is by storing the users GMT into his cookies, and retrieving it on the PHP process form.
u_gmt
explained:Date().getTimezoneOffset()
returns the offset to GMT-0 in minutesgetTimezoneOffset()
will return the offset to GMT-0 and not from GMT-0 we'll need to turn it around. How? simple, just by knowing that-*-=+
&-*+=-
. If you know basic math, you already know this principle.getTimezoneOffset()
will return the offset in minutes, so we just divide it by 60, so we can get the gmt offset format.Result:
(-(new Date().getTimezoneOffset()))/60
Now retrieve the cookie in PHP:
Replace
new DateTime(date('m/d/Y h:i:s a', time()));
withnew DateTime("UTC Time");
You can create a new
DateTimeZone()
object for each user input.Date/time/datetime values are stored in MySQL as you supply them. I.e. if you
INSERT
the string2012-04-17 12:03:23
into aDATETIME
column, that's the value that will be stored. It will be converted internally into a timestamp which may or may not be accurate (see below), but when you query for the value again, you'll get the same value back out; the roundtrip is transparent.Problems may occur if you try to do time calculations inside SQL. I.e. any operation that requires SQL to take the timezone and/or the server time into account. For example, using
NOW()
. For any of those operations, the timezone and/or server time should be set correctly. See Time Zone Problems.If that doesn't concern you and you only need to do calculations in PHP, you only need to make sure you know from which timezone to which timezone you want to convert. For that purpose it can be convenient to standardize all times to UTC, but it is not necessary, as timezone conversions from any timezone to any other timezone work just as well, as long as you're clear about which timezone you're converting from and to.
There is no reliable way to get the user's timezone. Timezone information is not sent in HTTP headers. The best that you could do is either: