Magento 2.1 – getCreatedAt() Returns UTC Time Instead of Local Time

magento-2.1sales-ordertimetimezone

I am trying to get the order time, I fixed the problem with orders with wrong time stamp in admin panel. Now I am trying to get the order date in my module.

The problem is

$created = $order->getCreatedAt() 

returns the UTC time and not local time. I tried to use

$created = $order->getCreatedAtStoreDate(); 

But this one returns nothing. How should I get the orders date?

Best Answer

You can use an instance of Timezone to convert it into store's timezone. Here is a very generic example.

namespace VendorName\ModuleName\MyDir;

class MyClass
{
    private $timezone;

    public function __construct(
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
    ) {
        $this->timezone = $timezone;
    }

    public function myMethod($order)
    {
        $created = $order->getCreatedAt();

        //Convert to store timezone
        $created = $this->timezone->date(new \DateTime($created));

        //To print or display this you can use following.
        //Feel free to tweak the format
        $dateAsString = $created->format('M j, Y g:i:s A');

        //Proceed further..
    }
}
Related Topic