php: setting a timezone by UTC offset
Solution 1:
how about this...
$original = new DateTime("now", new DateTimeZone('UTC'));
$timezoneName = timezone_name_from_abbr("", 3*3600, false);
$modified = $original->setTimezone(new DateTimezone($timezoneName));
Solution 2:
You said:
Using javascript I know that my users timezone is UTC +3.
You probably ran something like this:
var offset = new Date().getTimezoneOffset();
This returns the current offset from UTC in minutes, with positive values falling west of UTC. It does not return a time zone!
A time zone is not an offset. A time zone has an offset. It can have multiple different offsets. Often there are two offsets, one for standard time and one for daylight saving time. A single numeric value cannot represent this alone.
- Example of a time zone:
"America/New_York"
- Corresponding standard offset:
UTC-5
- Corresponding daylight offset:
UTC-4
- Corresponding standard offset:
Besides the two offsets, also wrapped up in that time zone are the dates and times for transitioning between the two offsets so you know when they apply. There's also a historical record of how the offsets and transitions may have changed over time.
See also "Time Zone != Offset" in the timezone tag wiki.
In your example case, you probably received a value of -180
from javascript, representing a current offset of UTC+3. But that's just the offset for that particular point in time! If you follow minaz's answer, you will get a time zone that makes the assumption that UTC+3 is always the correct offset. That would work if the real time zone is something like "Africa/Nairobi"
which has never used anything except UTC+3. But for all you know your user could be in "Europe/Istanbul"
, which uses UTC+3 in the summer and UTC+2 in the winter.
Solution 3:
Modern answer:
$usersNow = new DateTime('now', new DateTimeZone('+0300'));
Documentation:
http://php.net/manual/en/datetimezone.construct.php