LocalizedDateToUtcConverter.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. declare(strict_types=1);
  7. namespace Magento\Framework\Stdlib\DateTime\Timezone;
  8. use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
  9. use Magento\Framework\Locale\ResolverInterface;
  10. use Magento\Framework\App\Config\ScopeConfigInterface;
  11. /**
  12. * Class LocalizedDateToUtcConverter
  13. */
  14. class LocalizedDateToUtcConverter implements LocalizedDateToUtcConverterInterface
  15. {
  16. /**
  17. * Contains default date format
  18. *
  19. * @var string
  20. */
  21. private $defaultFormat = 'Y-m-d H:i:s';
  22. /**
  23. * @var TimezoneInterface
  24. */
  25. private $timezone;
  26. /**
  27. * @var ResolverInterface
  28. */
  29. private $localeResolver;
  30. /**
  31. * LocalizedDateToUtcConverter constructor.
  32. *
  33. * @param TimezoneInterface $timezone
  34. * @param ResolverInterface $localeResolver
  35. */
  36. public function __construct(
  37. TimezoneInterface $timezone,
  38. ResolverInterface $localeResolver
  39. ) {
  40. $this->timezone = $timezone;
  41. $this->localeResolver = $localeResolver;
  42. }
  43. /**
  44. * @inheritdoc
  45. */
  46. public function convertLocalizedDateToUtc($date)
  47. {
  48. $configTimezone = $this->timezone->getConfigTimezone();
  49. $locale = $this->localeResolver->getLocale();
  50. $formatter = new \IntlDateFormatter(
  51. $locale,
  52. \IntlDateFormatter::MEDIUM,
  53. \IntlDateFormatter::MEDIUM,
  54. $configTimezone
  55. );
  56. $localTimestamp = $formatter->parse($date);
  57. $gmtTimestamp = $this->timezone->date($localTimestamp)->getTimestamp();
  58. $formattedUniversalTime = date($this->defaultFormat, $gmtTimestamp);
  59. $date = new \DateTime($formattedUniversalTime, new \DateTimeZone($configTimezone));
  60. $date->setTimezone(new \DateTimeZone('UTC'));
  61. return $date->format($this->defaultFormat);
  62. }
  63. }