Magento, Magento 2

How to Get Current GMT Date Time in Magento 2

How to Get Current GMT Date Time in Magento 2

In this tutorial, Today I will explain to how to get current GMT Date Time in Magento 2. To get Current GMT Date Time Magento provide class for that \Magento\Framework\Stdlib\DateTime\DateTime. You need to inject it in your construct class to get GMT Date Time.

Follow this below way to get GMT Date Time :

You may also like this :

First of all, I created Helloworld.php block file at app/code/RH/Helloworld/Block/ and paste the below code. In your construct you need to inject class \Magento\Framework\Stdlib\DateTime\DateTime. After that,gmtDate() function will return current GMT Date Time.


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTimeFactory
     */
    protected $dateTimeFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateTimeFactory,
        array $data = []
    ) {
        $this->dateTimeFactory = $dateTimeFactory;
        parent::__construct($context, $data);
    }

    public function getCurrentGMTDateTime()
    {
        $dateModel = $this->dateTimeFactory->create();
        return $dateModel->gmtDate();
    }
}

You can use this code in your block file or any other files. Here, getCurrentGMTDateTime() function will return current GMT Date Time. You can see output of that function.

Output : 2021-03-11 17:31:26

That’s it !!!

I hope this blog is easy to understand how to get current GMT Date Time in Magento 2.In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged , ,