1

When I want to calculate a difference in days (using date1 and date2 as an example):

$date1 = '2019-03-27';
$date2 = '2019-04-01';

echo((strtotime($date2) - strtotime($date1)) / 86400);

The result is:

2

However doing the same with:

$date1 = '2019-03-27';
$date2 = '2019-04-01';

echo((strtotime($date2) - strtotime($date1)) / 86400);

Returns:

4.9583333333333

This could be fixed with: date_default_timezone_set('UTC');.

But why isn't PHP using the same timezones for certain dates by default?

Clydeston
  • 25
  • 1
  • 9
KrzysiekK
  • 53
  • 1
  • 4
  • I get "5" when I run on PHP 7.2 which make sense as 27,28,29,30,01 (as you divided by 86400 you actually counting days) – dWinder Feb 21 '19 at 13:43
  • 1
    1. Both code snippets are identical, and the first one does not produce that result. 2. There's a DST change somewhere around that timeframe in your timezone, that's why you get a fractional result. – deceze Feb 21 '19 at 13:48
  • And I get this x.958333 value on PHP Version 7.2.8-1+ubuntu16.04.1+deb.sury.org+1 which is an identical decimal part as someone who was posting here: https://stackoverflow.com/questions/1940338/date-difference-in-php-on-days#comment59916752_17444672 so I can't be the only one edit: @deceze you must be right, haven't thought about that! Thanks! – KrzysiekK Feb 21 '19 at 13:50
  • If I may recommend https://www.youtube.com/watch?v=-5wpm-gesOY… – deceze Feb 21 '19 at 13:55
  • Poor him. Damn you, timezones! :D – KrzysiekK Feb 21 '19 at 14:09

1 Answers1

2

There's a change from winter time to summer time sometime the end of March in your timezone, so one of the days is just 23 hours, so it doesn't divide cleanly by 86400 (24 hours).

deceze
  • 510,633
  • 85
  • 743
  • 889