Skip to content
Advertisement

PHP Time Conversion and Timezones

I’m trying to convert an RSS date (ISO 8601) to an iCalendar date. I thought I would turn the initial date time to a Unix timestamp, then format it with strftime.

I understand that strftime changes a date time to local time.

I am fetching the initial $date value from a WordPress RSS feed, configured to the Europe/Zurich timezone. The date fetched from RSS is correct (starting on Nov. 15th at 8am).

When I convert it, it gets an extra hour.

I had to set date_default_timezone_set('UTC') in order to keep the time unchanged.

$tz = "Europe/Zurich";
//date_default_timezone_set('UTC'); //not Europe/Zurich
$date = "2019-11-15T08:00:00+00:00";
$dt = strftime("%%Y%%m%%dT%%H%%M%%S", strtotime($date));

echo $date . "rn";
echo strtotime($date) . "rn";
echo $dt . "rn";

  • 2019-11-15T08:00:00+00:00
  • 20191115T090000

I get real confused working with timezones… The initial value is 8am in Zurich, but when transposed to the iCalendar date, even though the timezone is the same, it gets added that one hour.

What is the best way to handle this?

Advertisement

Answer

Try using the more modern DateTime class when working with dates:

$date = "2019-11-15T08:00:00+00:00";
$dtobj = new DateTime($date);

var_dump($dtobj);
echo date_default_timezone_get();
echo "n";
echo $dtobj->format("YmdThis");

On my system, this results in:

class DateTime#1 (3) {
  public $date =>
  string(26) "2019-11-15 08:00:00.000000"
  public $timezone_type =>
  int(1)
  public $timezone =>
  string(6) "+00:00"
}
America/Toronto
20191115T080000

As you can see, the object stores the timezone as a property, so the timezone on the system is no longer relevant.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement