TimeTrait.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * This file is part of the ramsey/uuid library
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. *
  8. * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
  9. * @license http://opensource.org/licenses/MIT MIT
  10. */
  11. declare(strict_types=1);
  12. namespace Ramsey\Uuid\Rfc4122;
  13. use DateTimeImmutable;
  14. use DateTimeInterface;
  15. use Ramsey\Uuid\Exception\DateTimeException;
  16. use Throwable;
  17. use function str_pad;
  18. use const STR_PAD_LEFT;
  19. /**
  20. * Provides common functionality for getting the time from a time-based UUID
  21. *
  22. * @psalm-immutable
  23. */
  24. trait TimeTrait
  25. {
  26. /**
  27. * Returns a DateTimeInterface object representing the timestamp associated
  28. * with the UUID
  29. *
  30. * @return DateTimeImmutable A PHP DateTimeImmutable instance representing
  31. * the timestamp of a time-based UUID
  32. */
  33. public function getDateTime(): DateTimeInterface
  34. {
  35. $time = $this->timeConverter->convertTime($this->fields->getTimestamp());
  36. try {
  37. return new DateTimeImmutable(
  38. '@'
  39. . $time->getSeconds()->toString()
  40. . '.'
  41. . str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT)
  42. );
  43. } catch (Throwable $e) {
  44. throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e);
  45. }
  46. }
  47. }