Background
I have a list of events that are set to a certain (UK) time. I want users to see the time of the event in their local time. For example: if an event starts at
20:30
UK time a user from the Netherlands should see the start time as 21:30
.Problem
I've got everything set up, and am creating new
DateTime
objects to set my events to. However, when I specify my DateTimeZone
object it shows +00:00
in stead of the DateTimeZone
I have created for it. This means that the new times are incorrect. So time that were set to 20:30
UK time still roll out as 20:30
NL time in stead of 21:30
.
Code
This is the code I've written. As far as I'm aware everything I'm doing is correct, but the
DateTimeZone
is still incorrect when assigned to the DateTime
object.
The default setting:
date_default_timezone_set('Europe/London');
The code that should convert DateTime
objects to local time:
$user_timezone = Helper::get_user_timezone(); //contains "Europe/Amsterdam"
foreach($events as $event){
$timestamp = $event->getDatetime()->getTimestamp();
$local_datetime = new DateTime('@'.$timestamp, new DateTimeZone($user_timezone));
}
Input
I'll use the following
DateTime
object as input:
DateTime Object
(
[date] => 2015-02-14 19:30:00.000000
[timezone_type] => 3
[timezone] => Europe/London
)
Output
This outputs the following
DateTime
object for me:
DateTime Object
(
[date] => 2015-02-14 19:30:00.000000
[timezone_type] => 1
[timezone] => +00:00
)
What have I tried
I've tried multiple things. Mostly it was about the order I set the
DateTimeZone
.
- I tried creating a
DateTimeZone
before the creation of theDateTime
object. I made sure it was a correct object and set it in theDateTime
constructor then. - I tried creating a
DateTime
object first with just a timestamp as parameter, and setting theDateTimeZone
object afterwards (I know there is/was a bug that caused some weird behaviour with settingDateTimeZone
directly). - I've made sure the timezone I want to set (
Europe/Amsterdam
) is legit according to the docs.
I'm starting to wonder if it's not possible to convert the date when using a timestamp
?
I have also looked at these question for the basic gist, but they have no such problem:
1. Converting between timezones in PHP
2. How to convert between time zones in PHP using the DateTime class?
I followed a couple more, but I can't find them at the moment.
Question
Why is my
DateTime
object getting an incorrect DateTimeZone
?
Edit
After checking again that my
DateTimeZone
objects are correct I get the following:
DateTimeZone Object
(
[timezone_type] => 3
[timezone] => Europe/Amsterdam
)
But when I set it to the new DateTime
object both the timezone_type
and timezone
change to:
DateTime Object
(
[date] => 2015-02-14 19:30:00.000000
[timezone_type] => 1
[timezone] => +00:00
)
You'll notice the different timezone_type
and timezone
.