Search code examples
phpdatetimedateinterval

PHP datetime diff wrong


I am trying to get a difference between two DateTime objects in PHP and the answer seems to be wrong. As you can see the diff() function gives a time difference of 4 hours and 41 minutes, but the time difference is clearly much closer to 7 hours.

$eastern_tz = new DateTimeZone( "US/Eastern" );

$now         = new DateTime( "now", $eastern_tz );
$future_date = new DateTime( $future_date_string ); //'2011-05-11 12:00:00'

$future_date->setTimezone( $eastern_tz );

$interval = $future_date->diff( $now );

var_dump( $now );
var_dump( $future_date );
var_dump( $interval );

return $interval->format( $format ); //"%d days, %h hours, %i minutes, %s seconds"

//DEBUG information

object(DateTime)[483]
  public 'date' => string '2016-06-15 09:18:41' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'US/Eastern' (length=10)
object(DateTime)[484]
  public 'date' => string '2016-06-15 14:00:00' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'US/Eastern' (length=10)
object(DateInterval)[479]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 0
  public 'h' => int 4
  public 'i' => int 41
  public 's' => int 19
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 0
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0

Solution

  • When you create $future_date = new DateTime( $future_date_string );, which is the default PHP timezone?

    $future_date->setTimezone( $eastern_tz ); is only needed if you render the date or if you import a new string. It's too late for parsing $future_date_string.