views:

1597

answers:

4

I have a Unix timestamp that comes from a database that is (unfortunately) in a timezone with a certain of either +3600 or +7200, depending on if it's DST or not. This has never been a problem before, but our website is currently moving to a more international audience and because of Javascript interaction with said timestamps, I need to convert the timestamp without any offset.

So, how do I, given just a Unix timestamp, get the offset for the timezone, at the moment of that timestamp? I'm looking through the PHP docs, but there's so many date/time functions I'm a bit lost.

I'm using PHP 5.2.3

A: 

Would this do the trick?

$tz = date("O", $time);

You could also do:

From here:

http://www.php.net/manual/en/function.date.php

Mike A.
Of course, that would only work going forward, since you don't know just from the Unix timestamp what the timezone is when it was created.
Mike A.
+2  A: 

You can't do that in the general case. A Unix timestamp is just the number of seconds since the Unix epoch, and does not contain any timestamp information.

One thing that might work for you is working out whether or not a given timestamp occurs during a time when DST is in effect, and then adjust accordingly. That approach would fail around the boundaries though (since there are 2 meanings for each timestamp in the hour immediately after DST begins and immediately before it ends).

In future, you're probably better off storing timestamps in UTC, to avoid precisely this sort of problem.

Dominic Rodger
Yeah, I know how I *should* be storing the timestamps, but there was a lot of existing data like this when I started working here. So I just go with the flow...
Aistina
Unix time is UTC, it has offset 0 and no DST adjustments. There is no need to adjust your unix timestamp.
Kjetil Jorgensen
The timestamps come from the PHP ``time()`` function. It gets the unix time and applies the timezone offset of the server.
Aistina
@kjetijor - that's true, but I think by "Unix timestamp", the OP was referring just to a number that represents the number of seconds since Jan 1, 1970 00:00, in some timezone (which appears from his answer to have been GMT with daylight-savings adjustments).
Dominic Rodger
A: 

If you by unix timestamp mean unix time (seconds since Epoch), the offset is always 0. Epoch is defined as 00:00:00 UTC, January 1, 1970. Note the UTC, which has offset 0.

Application of timezone offset and dst is handled by the libraries that convert the unix timestamp into date/time structures. (I don't know php, but i.e. in C, the localtime function takes a unix timestamp, applies timezone information either from environment or the /etc/localtime file, and spits out a struct of seconds, minutes, hours, and so on).

Kjetil Jorgensen
+2  A: 

I feel silly again answering my own question, but I just found the gmstrftime function. It seems to do exactly what I want. Thanks everyone though!

Aistina