Get current UTC datetime:
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
*/
$dateTime->date();
Get current datetime in store timezone:
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
*/
$timezone->date(new \DateTime())->format('Y-m-d H:i:s');
Note that all datetimes stored in Magento database are in UTC.
To debug your store datetime, you can try this code:
$currentPhpDateTime = new \DateTime();
/**
* @var \Magento\Framework\Stdlib\DateTime\DateTime $dateTime
*/
$currentMagentoDateTime = $dateTime->date();
/**
* @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
*/
$currentLocalizedMagentoDateTime = $timezone->date($currentPhpDateTime)->format('Y-m-d H:i:s');
dump($currentPhpDateTime->format('Y-m-d H:i:s')); // output: current datetime in UTC
dump($currentMagentoDateTime); // output: current datetime in UTC
dump($currentLocalizedMagentoDateTime); // output: current datetime in timezone you set in Magento configuration
You will see something similar to these outputs:
"2019-08-28 00:00:00"
"2019-08-28 00:00:00"
"2019-08-28 07:00:00"
The first and second outputs are current date in UTC. The third one is current date in timezone you set in Magento configuration.
Note that date constructed using new \DateTime()
is in UTC, because Magento set your default timezone to UTC while bootstraping the app. In Magento 2.3.2, you can see how Magento set your default timezone in file app/bootpstrap.php
line 73:
date_default_timezone_set('UTC');