Skip to content

Commit

Permalink
Merge pull request #6159 from kenjis/fix-Time-getAget
Browse files Browse the repository at this point in the history
fix: Time::getAge() calculation
  • Loading branch information
samsonasik authored Jun 21, 2022
2 parents eac264e + 4e7c3df commit 0180479
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
7 changes: 2 additions & 5 deletions system/I18n/Time.php
Original file line number Diff line number Diff line change
Expand Up @@ -452,19 +452,16 @@ public function getWeekOfYear(): string
}

/**
* Returns the age in years from the "current" date and 'now'
* Returns the age in years from the date and 'now'
*
* @throws Exception
*
* @return int
*/
public function getAge()
{
$now = self::now()->getTimestamp();
$time = $this->getTimestamp();

// future dates have no age
return max(0, date('Y', $now) - date('Y', $time));
return max(0, $this->difference(self::now())->getYears());
}

/**
Expand Down
33 changes: 31 additions & 2 deletions tests/system/I18n/TimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -382,19 +382,48 @@ public function testGetTimestamp()
public function testGetAge()
{
$time = Time::parse('5 years ago');

$this->assertSame(5, $time->getAge());
$this->assertSame(5, $time->age);
}

public function testAgeNow()
{
$time = new Time();
$this->assertSame(0, $time->age);

$this->assertSame(0, $time->getAge());
}

public function testAgeFuture()
{
Time::setTestNow('June 20, 2022', 'America/Chicago');
$time = Time::parse('August 12, 2116 4:15:23pm');
$this->assertSame(0, $time->age);

$this->assertSame(0, $time->getAge());
}

public function testGetAgeSameDayOfBirthday()
{
Time::setTestNow('December 31, 2022', 'America/Chicago');
$time = Time::parse('December 31, 2020');

$this->assertSame(2, $time->getAge());
}

public function testGetAgeNextDayOfBirthday()
{
Time::setTestNow('January 1, 2022', 'America/Chicago');
$time = Time::parse('December 31, 2020');

$this->assertSame(1, $time->getAge());
}

public function testGetAgeBeforeDayOfBirthday()
{
Time::setTestNow('December 30, 2021', 'America/Chicago');
$time = Time::parse('December 31, 2020');

$this->assertSame(0, $time->getAge());
}

public function testGetQuarter()
Expand Down

0 comments on commit 0180479

Please sign in to comment.