Aistina
Aistina

Reputation: 12683

Get timezone offset in PHP given a unix timestamp

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

Upvotes: 3

Views: 20834

Answers (5)

BCsongor
BCsongor

Reputation: 869

U can use this:

$timezone_offset = date('O');

It will return the difference to Greenwich time (GMT) in hours.

[source]

Upvotes: 1

Aistina
Aistina

Reputation: 12683

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!

Upvotes: 4

Kjetil Joergensen
Kjetil Joergensen

Reputation: 1635

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).

Upvotes: 1

Dominic Rodger
Dominic Rodger

Reputation: 99751

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.

Upvotes: 2

Mike A.
Mike A.

Reputation: 398

Would this do the trick?

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

You could also do:

From here:

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

Upvotes: 0

Related Questions