Skip to content

Commit e8f833a

Browse files
authored
fix: correct age calculation and improve code formatting (#405)
1 parent c7da7b6 commit e8f833a

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

src/System/Time/Now.php

+4-3
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public function __construct(string $date_format = 'now', ?string $time_zone = nu
6262
if (null !== $time_zone) {
6363
$time_zone = new \DateTimeZone($time_zone);
6464
}
65-
$this->date = new \DateTime($date_format, $time_zone);
65+
$this->date = new \DateTime($date_format, $time_zone);
6666

6767
$this->refresh();
6868
}
@@ -126,8 +126,9 @@ private function refresh(): void
126126
$this->timeZone = $this->date->format('e');
127127
$this->shortDay = $this->date->format('D');
128128

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

133134
private function current(string $format, int $timestamp): string

tests/Time/TimeTravelTest.php

+4-2
Original file line numberDiff line numberDiff line change
@@ -155,9 +155,11 @@ public function itSameWithCustumeTime(): void
155155
*/
156156
public function itCorrectAge(): void
157157
{
158-
$now = new Now('01/01/2000');
158+
$now = new Now('01/01/2000');
159+
$currentYear = (int) date('Y');
160+
$expectedAge = $currentYear - 2000;
159161
$this->assertSame(
160-
24.0,
162+
$expectedAge,
161163
$now->age,
162164
'the age must equal'
163165
);

0 commit comments

Comments
 (0)