オレオレ ミニマム Date クラス in PHP
code:php
<?php
declare(strict_types=1);
class SimpleDate implements Stringable
{
public function __construct(
private readonly int $year,
private readonly int $month,
private readonly int $day,
) {
}
public static function createFromDateTimeInterface(DateTimeInterface $datetime): self
{
return new self(
(int) $datetime->format('Y'),
(int) $datetime->format('m'),
(int) $datetime->format('d'),
);
}
public function toDateTime(DateTimeZone $timezone = null): DateTimeInterface
{
return DateTimeImmutable::createFromFormat('!Y-m-d', (string)$this, $timezone);
}
public function __toString(): string
{
return sprintf('%04d-%02d-%02d', $this->year, $this->month, $this->day);
}
public function year(): int
{
return $this->year;
}
public function month(): int
{
return $this->month;
}
public function day(): int
{
return $this->day;
}
}