Skip to content

Commit

Permalink
Merge pull request #291 from cakephp/fix-diffmonthsignoretimezone
Browse files Browse the repository at this point in the history
Fix diffInMonthsIgnoreTimezone() using wrong timezone
  • Loading branch information
othercorey authored Apr 7, 2021
2 parents 141967a + 1785e26 commit 1d187c7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 13 deletions.
2 changes: 1 addition & 1 deletion src/Traits/DifferenceTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function diffInMonthsIgnoreTimezone(?ChronosInterface $dt = null, bool $a
$dt = $dt ?? static::now($this->tz);
$dt = new static($dt->format('Y-m-d H:i:s.u'), $utcTz);

return $this->diffInMonths($dt, $abs);
return $source->diffInMonths($dt, $abs);
}

/**
Expand Down
23 changes: 11 additions & 12 deletions tests/TestCase/DateTime/DiffTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Cake\Chronos\ChronosInterval;
use Cake\Chronos\Test\TestCase\TestCase;
use Closure;
use DateTimeZone;

class DiffTest extends TestCase
{
Expand Down Expand Up @@ -134,19 +135,17 @@ public function testDiffInMonthsEnsureIsTruncated($class)
*/
public function testDiffInMonthsIgnoreTimezone($class)
{
$start = $class::createFromDate(2019, 06, 01, 'Asia/Tokyo');
foreach ([1, 2, 3, 4, 5] as $monthOffset) {
$end = $class::createFromDate(2019, 6 + $monthOffset, 01, 'Asia/Tokyo');
$this->assertSame($monthOffset, $start->diffInMonthsIgnoreTimezone($end));
}

$start = $class::createFromDate(2019, 06, 01, 'UTC');
$end = $class::createFromDate(2019, 10, 01, 'UTC');
$this->assertSame(4, $start->diffInMonthsIgnoreTimezone($end));
$tokyoStart = new $class('2019-06-01', new DateTimeZone('Asia/Tokyo'));
$utcStart = new $class('2019-06-01', new DateTimeZone('UTC'));
foreach (range(1, 6) as $monthOffset) {
$end = new $class(sprintf('2019-%02d-01', 6 + $monthOffset), new DateTimeZone('Asia/Tokyo'));
$this->assertSame($monthOffset, $tokyoStart->diffInMonthsIgnoreTimezone($end));
$this->assertSame($monthOffset, $utcStart->diffInMonthsIgnoreTimezone($end));

$start = $class::createFromDate(2019, 06, 01, 'UTC');
$end = $class::createFromDate(2019, 10, 01, 'Asia/Tokyo');
$this->assertSame(4, $start->diffInMonthsIgnoreTimezone($end));
$end = new $class(sprintf('2020-%02d-01', 6 + $monthOffset), new DateTimeZone('Asia/Tokyo'));
$this->assertSame($monthOffset + 12, $tokyoStart->diffInMonthsIgnoreTimezone($end));
$this->assertSame($monthOffset + 12, $utcStart->diffInMonthsIgnoreTimezone($end));
}

$this->wrapWithTestNow(function () use ($class) {
$this->assertSame(1, $class::now()->subMonth()->startOfMonth()->diffInMonthsIgnoreTimezone());
Expand Down

0 comments on commit 1d187c7

Please sign in to comment.