BlondeSwan
BlondeSwan

Reputation: 782

DateTimeZone only handles offsets in one direction

I am attempting to retrieve a date that is not in GMT and convert it to GMT. To do this, I am creating two time zones (one GMT and one non-GMT) and attempting to get the offset between them. However, the offset is only correct in one direction. For this specific example, I am trying to compare GMT +4 to GMT. I expect to get 4hrs (14400 seconds) when I compare the the GMT timezone to the GMT+4 timezone, and -4hrs (-14400 seconds) when I compare the GMT+4 timezone to GMT. However, when comparing the later I'm getting 0... Here is what I have

$default_timezone = new DateTimeZone(drupal_get_user_timezone());
$default_reg_date = new DateTime($reg_date_string, $default_timezone);

$gmt_timezone = new DateTimeZone('UTC');
$gmt_reg_date = new DateTime($reg_date_string, $gmt_timezone);

// Returns as 14400
$default_gmt_offset = $default_timezone->getOffset($gmt_reg_date);

// Returns as 0
$gmt_default_offset = $gmt_timezone->getOffset($default_reg_date); 

Why can't I get the right number, what am I doing wrong? Does retrieving the offset only work one way?

Note: in this specific example, drupal_get_user_timezone() is returning GMT+4

Upvotes: 1

Views: 53

Answers (1)

Joffrey Schmitz
Joffrey Schmitz

Reputation: 2438

From the PHP documentation :

This function returns the offset to GMT for the date/time specified in the datetime parameter. The GMT offset is calculated with the timezone information contained in the DateTimeZone object being used.

The function works with 2 logics steps :

  1. Convert the date into the timezone on which the function is applied
  2. Get the offset from GMT

So calling this function on new DateTimeZone('UTC') will always returns 0

If you want to convert a date into UTC, you can use the setTimeZone function :

$date_string = '2020-05-01 09:11:00' ;
$date = new DateTime($date_string, new DateTimeZone('Europe/Brussels'));
echo $date->format('c') ; // 2020-05-01T09:11:00+02:00

$date->setTimeZone(new DateTimeZone('UTC'));
echo $date->format('c') ; // 2020-05-01T07:11:00+00:00

Upvotes: 2

Related Questions