phpnoob phpnoob - 4 months ago 8
PHP Question

date_default_timezone_set is producing weird results, what gives?

I need to use date_default_timezone_set for my project and it all worked fine until I started using date_diff, as it is producing good and false results depending on the chosen timezone.
An example:

date_default_timezone_set('America/Los_Angeles');

$first = date_create("2016-10-01");
$last = date_create("2016-10-31");
$diff = date_diff($first, $last);
echo $diff->d;


The result is 30, wich is correct.
Now, If I set the timezone to Europe:

date_default_timezone_set('Europe/London');


The result is 0.
What's going on?

Answer

If you var_dump($diff) you will see that the days has reset to zero and month has incremented to 1:

object(DateInterval)#3 (15) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(1)
  ["d"]=>
  int(0)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  int(30)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

This is probably due to the fact that London switches back from DST on the last Sunday in October. However the date difference is calculated that apparently makes it a "month" as opposed to 30 days.

You can overcome this by using the days property which is will report 30:

$first = date_create("2016-10-01");
$last = date_create("2016-10-31");
$diff = date_diff($first, $last);
echo $diff->days;