Skip to content

Time zone bug with \DateTimeInterface::diff() #9866

Closed
@jack-worman

Description

@jack-worman

Description

The following code:

<?php

function getYearsBetween(
    \DateTimeImmutable $startDate,
    \DateTimeImmutable $endDate,
): int {
    $dateInterval = $startDate->diff($endDate, true);
    return $dateInterval->y;
}

$start = new \DateTimeImmutable('2000-11-01 09:29:22.907606', new \DateTimeZone('America/Chicago'));
$end = new \DateTimeImmutable('2022-06-06 11:00:00.000000', new \DateTimeZone('America/New_York'));
$result = getYearsBetween($start, $end);
var_export($result);

Resulted in this output:

-22

But I expected this output instead:

21

There seems to be a timezone issue that breaks \DateIntervals
Works (same time zones): https://3v4l.org/RK34h
Does not work (different time zones): https://3v4l.org/nmPAj

In the mean time, I will be ensuring both \DateTimeImmutables are in the same timezone before calling ->diff()

PHP Version

>= 8.1.10

Operating System

No response

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions