Theo Kouzelis
Theo Kouzelis

Reputation: 3523

Converting Timeszones in PHP

I have a script that brings in RSS feeds that come from different timezones. I then publish the RSS feeds with a twitter style time display saying "posted about 10 minutes ago". But because I cant convert these times into my GMT timezone this display shows the wrong time eg a post from EST always says "about 5 hours ago" when it is new.

I have looked around to find solutions but none of them seem to work for me I wonder if you can tell me where I am going wrong.

$dbTimezone = new DateTimeZone($dbStoredTimezone); //$dbStoredTimezone = 'EST'
$dbDate = new DateTime($dbStoredDate, $dbTimezone); //$dbStoredDate = '2012-03-01 05:27:26'
$gmtTimezone = new DateTimeZone('GMT');
echo $gmtTimezone->getOffset($dbDate); //always echo's 0
$offset = DateInterval::createFromDateString ($gmtTimezone->getOffset($dbDate));
$dbDate->add($offset);

Upvotes: 1

Views: 261

Answers (1)

kernel
kernel

Reputation: 3743

The problem seems to be in your $gmtTimezone = new DateTimeZone('GMT');. Because getOffset() returns the offset from GMT (see here: http://www.php.net/manual/en/datetimezone.getoffset.php). This is exactly why it always returns 0.

If you use the DateTime::getOffset() method it should work.

Here's your edited code:

<?php
$dbTimezone = new DateTimeZone($dbStoredTimezone); //$dbStoredTimezone = 'EST'
$dbDate = new DateTime($dbStoredDate, $dbTimezone);
echo $dbDate->getOffset();
$offset = DateInterval::createFromDateString ($dbDate->getOffset());
$dbDate->add($offset);

My result is -18000.

Upvotes: 1

Related Questions