Skip to content

Commit

Permalink
Implemented 'getDate'.
Browse files Browse the repository at this point in the history
Signed-off-by: Johannes Tegnér <[email protected]>
  • Loading branch information
Johannestegner committed Jan 21, 2024
1 parent d2cc664 commit 6cddad7
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Personnummer.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ private static function getParts(string $ssn): array
}

$parts['fullYear'] = $parts['century'] . $parts['year'];

$parts['original'] = $ssn;
return $parts;
}
Expand Down Expand Up @@ -230,6 +229,14 @@ public function getAge(): int
return (new DateTime())->diff($birthday)->y;
}

public function getDate(): DateTime
{
return DateTime::createFromFormat(
'Ymd',
$this->parts['fullYear'] .$this->parts['month'] . $this->parts['realDay']
);
}

public function __get(string $name)
{
if (isset($this->parts[$name])) {
Expand Down
8 changes: 8 additions & 0 deletions src/PersonnummerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Personnummer;

use DateTime;
use Exception;

/**
Expand Down Expand Up @@ -89,4 +90,11 @@ public function __construct(string $ssn, array $options = []);
* @throws Exception When date is invalid or problems with DateTime library
*/
public function getAge(): int;

/**
* Get the date part of the personnummer as a DateTime object.
*
* @return DateTime
*/
public function getDate(): DateTime;
}
25 changes: 25 additions & 0 deletions tests/PersonnummerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,4 +236,29 @@ public function testIsNotInterim(): void
}
}
}

public function testDate(): void
{
foreach (self::$testdataList as $testdata) {
if (!$testdata['valid']) {
continue;
}

$val = $testdata['long_format'];
if ($testdata['type'] === 'con') {
// If it's a coordination number, we aught to remove 60 from the "real day" to make sure
// we get the correct date.
$val = substr($testdata['long_format'], 0, 6); // YYMM
$val .= (int)substr($testdata['long_format'], 6, 2) - 60; // DD
}

$pn = Personnummer::parse($testdata['separated_format']);
$date = DateTime::createFromFormat('Ymd', substr($val, 0, 8)); // Only want YYYYMMDD

self::assertSame(
$pn->getDate()->format("Ymd"),
$date->format('Ymd')
);
}
}
}

0 comments on commit 6cddad7

Please sign in to comment.