Skip to content

Commit

Permalink
fix: correct age calculation and improve code formatting (#405)
Browse files Browse the repository at this point in the history
  • Loading branch information
SonyPradana authored Dec 30, 2024
1 parent c7da7b6 commit e8f833a
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
7 changes: 4 additions & 3 deletions src/System/Time/Now.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function __construct(string $date_format = 'now', ?string $time_zone = nu
if (null !== $time_zone) {
$time_zone = new \DateTimeZone($time_zone);
}
$this->date = new \DateTime($date_format, $time_zone);
$this->date = new \DateTime($date_format, $time_zone);

$this->refresh();
}
Expand Down Expand Up @@ -126,8 +126,9 @@ private function refresh(): void
$this->timeZone = $this->date->format('e');
$this->shortDay = $this->date->format('D');

$age = time() - $this->date->getTimestamp();
$this->age = abs(floor($age / (365 * 60 * 60 * 24)));
$now = new \DateTime('now', new \DateTimeZone($this->timeZone));
$interval = $now->diff($this->date);
$this->age = $interval->y;
}

private function current(string $format, int $timestamp): string
Expand Down
6 changes: 4 additions & 2 deletions tests/Time/TimeTravelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,11 @@ public function itSameWithCustumeTime(): void
*/
public function itCorrectAge(): void
{
$now = new Now('01/01/2000');
$now = new Now('01/01/2000');
$currentYear = (int) date('Y');
$expectedAge = $currentYear - 2000;
$this->assertSame(
24.0,
$expectedAge,
$now->age,
'the age must equal'
);
Expand Down

0 comments on commit e8f833a

Please sign in to comment.