DateTimeImmutable.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog;
  11. use DateTimeZone;
  12. /**
  13. * Overrides default json encoding of date time objects
  14. *
  15. * @author Menno Holtkamp
  16. * @author Jordi Boggiano <j.boggiano@seld.be>
  17. */
  18. class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
  19. {
  20. /**
  21. * @var bool
  22. */
  23. private $useMicroseconds;
  24. public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null)
  25. {
  26. $this->useMicroseconds = $useMicroseconds;
  27. parent::__construct('now', $timezone);
  28. }
  29. public function jsonSerialize(): string
  30. {
  31. if ($this->useMicroseconds) {
  32. return $this->format('Y-m-d\TH:i:s.uP');
  33. }
  34. return $this->format('Y-m-d\TH:i:sP');
  35. }
  36. public function __toString(): string
  37. {
  38. return $this->jsonSerialize();
  39. }
  40. }