Search code examples
phpdatetimedst

DateTime::diff and end of Daylight Saving Time


At last weekend we had end of DST and clocks were turned backward 1 hour. I've found a strange behaviour of DateTime::diff() when compared date are in different times: spring time and winter time.

new DateTime('2015-10-28 12:50:00')->diff(new DateTime('2015-10-19 13:20:00'))

result = {DateInterval} [15]
    y = 0
    m = 0
    d = 9
    h = -1   # negative hour!
    i = 30
    s = 0

when the difference is more than one hour everythin is ok:

new DateTime('2015-10-28 12:50:00')->diff(new DateTime('2015-10-19 14:20:00'))

result = {DateInterval} [15]
    y = 0
    m = 0
    d = 8
    h = 22
    i = 30
    s = 0

Any ideas how to fix this? Is this a bug in PHP?


Solution

  • Yes, this is a bug PHP currently doesn't handle DST transitions. Bug reports #51051 (still open) and #55253 (fixed in PHP 5.3.9) describe the problems you're having.Best practice is to do all your date calculations in UTC, which avoids this problem. See this post for further details