|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace Darsyn\DateTime; |
| 4 | + |
| 5 | +class DateTime extends \DateTimeImmutable implements DateTimeInterface |
| 6 | +{ |
| 7 | + /** {@inheritdoc} */ |
| 8 | + public function __construct(?string $datetime = null, ?\DateTimeZone $timezone = null) |
| 9 | + { |
| 10 | + $datetime = new \DateTime($datetime ?: 'now', $timezone); |
| 11 | + parent::__construct($datetime->format('Y-m-d\TH:i:s.000000P'), $timezone); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * {@inheritdoc} |
| 16 | + * @throws \InvalidArgumentException |
| 17 | + */ |
| 18 | + public static function createFromFormat($format, $time, ?\DateTimeZone $timezone = null): self |
| 19 | + { |
| 20 | + // DateTimeImmutable's createFromFormat() method returns instances of DateTimeImmutable rather than static |
| 21 | + // (child class), so we'll unfortunately have to replicate some of the constructor logic here. |
| 22 | + if (!\is_object($datetime = \DateTime::createFromFormat($format, $time, $timezone))) { |
| 23 | + throw new \InvalidArgumentException('Value not compatible with date format.'); |
| 24 | + } |
| 25 | + return new static($datetime->format(DateTimeInterface::NO_TIMEZONE), $datetime->getTimezone()); |
| 26 | + } |
| 27 | + |
| 28 | + /** {@inheritdoc} */ |
| 29 | + public static function createFromMutable($datetime): self |
| 30 | + { |
| 31 | + return static::createFromObject($datetime); |
| 32 | + } |
| 33 | + |
| 34 | + /** {@inheritdoc} */ |
| 35 | + public static function createFromObject(\DateTimeInterface $datetime): DateTimeInterface |
| 36 | + { |
| 37 | + return new static($datetime->format(DateTimeInterface::NO_TIMEZONE), $datetime->getTimezone()); |
| 38 | + } |
| 39 | + |
| 40 | + /** {@inheritdoc} */ |
| 41 | + public static function createFromTimestamp(int $timestamp): DateTimeInterface |
| 42 | + { |
| 43 | + return static::createFromFormat('U', (string) $timestamp); |
| 44 | + } |
| 45 | + |
| 46 | + /** {@inheritdoc} */ |
| 47 | + public function jsonSerialize(): string |
| 48 | + { |
| 49 | + return $this->__toString(); |
| 50 | + } |
| 51 | + |
| 52 | + /** {@inheritdoc} */ |
| 53 | + public function __toString(): string |
| 54 | + { |
| 55 | + return $this->format(DateTimeInterface::RFC3339); |
| 56 | + } |
| 57 | +} |
0 commit comments