4

I'm trying to work around problem with php DateTime witch returns me weird values in some specific cases.

For example, my code:

$start = new \DateTime("2018-10-04 00:00");
$end = new \DateTime("2018-10-28 23:59");
$diff = $end->diff($start);

returns:

DateInterval {#2311 ▼
  +"y": 0
  +"m": 0
  +"d": 25
  +"h": -1
  +"i": 59
  +"s": 59
  +"f": 0.0
  +"weekday": 0
  +"weekday_behavior": 0
  +"first_last_day_of": 0
  +"invert": 1
  +"days": 24
  +"special_type": 0
  +"special_amount": 0
  +"have_weekday_relative": 0
  +"have_special_relative": 0
}

"25 days -1 hour 59 minutes".

Function works perfect in most cases. This happens only sometimes, but still being a problem... Is there any way to get normal format of days/hours without recalculating this weird values every time?

Krzysiu Jarzyna
  • 391
  • 2
  • 8

1 Answers1

0

Thanks to Alvaro i found the solution:

$start = new \DateTime("2018-10-04 00:00", new \DateTimeZone('UTC'));
$end = new \DateTime("2018-10-28 23:59", new \DateTimeZone('UTC'));
$diff = $end->diff($start);

The problem was probably my Europe/Warsaw timezone and CEST/CET timeshift during above period.

Krzysiu Jarzyna
  • 391
  • 2
  • 8
  • 1
    Please note this doesn't render totally correct results if the dates are meant to be in local time. In such case you'd need to create instances in local time and then [switch](http://php.net/manual/en/datetime.settimezone.php) to UTC. – Álvaro González Oct 12 '18 at 10:24
  • Works with all my dataset, but You are probably right. You can always change TimeZone if You need it. – Krzysiu Jarzyna Oct 12 '18 at 10:28