Fooman

Magento 2 handling of order timezone




Triggered by a recent discussion on Slack and noticing this latest Pull Request to fix some timezone handling specific code in the Magento 2 framework (Github PR) it seems to confirm a long held suspicion that something in the Magento framework timezone handling was not quite working the way I believe it should (even going back to M1 days). Below is an approach similar to what I have been using to translate for example the order date to the timezone of the store. It would be able to handle any Magento model that descends from \Magento\Framework\DataObject and has getCreatedAt() and getStoreId() methods.

class CreationTimeAtTimezone

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
    }

    public function getCreatedAtStore(\Magento\Framework\DataObject $object, $format = 'Y-m-d')
    {
        $datetime = \DateTime::createFromFormat('Y-m-d H:i:s', $object->getCreatedAt());
        $timezone = $this->scopeConfig->getValue(
            'general/locale/timezone',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $object->getStoreId()
        );
        if ($timezone) {
            $storeTime = new \DateTimeZone($timezone);
            $datetime->setTimezone($storeTime);
        }
        return $datetime->format($format); 
    }
}    
Kristof Ringleff

Kristof Ringleff

Founder and Lead Developer at Fooman

Join the Fooman Community

We send our popular Fooman Developer Monthly email with Magento news, articles & developer tips, as well as occasional Fooman extension updates.