fix: getAge() calculation

This commit is contained in:
kenjis 2022-06-20 08:02:45 +09:00
parent 25feb6f2bc
commit efef8eb702
No known key found for this signature in database
GPG Key ID: BD254878922AF198
2 changed files with 29 additions and 4 deletions

View File

@ -452,7 +452,7 @@ class Time extends DateTime
}
/**
* Returns the age in years from the "current" date and 'now'
* Returns the age in years from the date and 'now'
*
* @throws Exception
*
@ -460,11 +460,12 @@ class Time extends DateTime
*/
public function getAge()
{
$now = self::now()->getTimestamp();
$time = $this->getTimestamp();
$now = self::now();
$age = (int) (((int) $now->format('Ymd') - (int) $this->format('Ymd')) / 10000);
// future dates have no age
return max(0, date('Y', $now) - date('Y', $time));
return max(0, $age);
}
/**

View File

@ -402,6 +402,30 @@ final class TimeTest extends CIUnitTestCase
$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()
{
$time = Time::parse('April 15, 2015');