31

In Magento 1.x you could get the store date time via

Mage::getModel('core/date')->gmtDate();

What would be the equivalent to this in Magento 2.x?

2
  • does this return the current store time? I am getting the GMT time instead of PST time that Magento 2 store is set to. May 14, 2020 at 6:22
  • 1
    \Magento\Framework\Stdlib\DateTime\DateTime $date will return UTC (GMT). Use Magento\Framework\Stdlib\DateTime\TimezoneInterface::formatDate(); for the current store date and time.
    – Eirik
    May 14, 2020 at 7:21

7 Answers 7

56

You need to inject in your class constructor an instance of \Magento\Framework\Stdlib\DateTime\DateTime and use that one.
Something like this:

protected $date;
public function __construct(
    ....
    \Magento\Framework\Stdlib\DateTime\DateTime $date,
    ....
) {
    ....
    $this->date = $date;
    ....
}

Then, you can use in your class this:

$date = $this->date->gmtDate();
6
  • 1
    it gives gmt date how to get current store timezone wise date
    – ND17
    Feb 1, 2016 at 12:00
  • I have tried this but it always giving a time difference of 5 hrs can you help me
    – Naveenbos
    Mar 28, 2017 at 5:25
  • How to get only time ? Aug 25, 2017 at 6:21
  • 3
    @SanjayGohil. the method gmtDate shown above accepts 2 optional parameters. The first one is $format which defaults to Y-m-d H:i:s. You can just call the method with the parameter you want gmtDate('H:i:s') or any other time format.
    – Marius
    Aug 25, 2017 at 6:34
  • How to add/subtract months into/from date by this method ?
    – Ajwad Syed
    Jul 3, 2019 at 14:22
24

To get UTC date in Magento2 you should use \Magento\Framework\Stdlib\DateTime\DateTime::gmtDate();

You should inject dependency on this class via construct and then use this function. See this class for more date/time related methods.

In your code sample you are retrieving UTC date, not store date. To get date formatted according to the timezone of the current store, use Magento\Framework\Stdlib\DateTime\TimezoneInterface::formatDate(); (again, by injecting dependency to construct)

2
  • For current store timezone this function give me only date not time so how can i get time also?
    – ND17
    Feb 1, 2016 at 11:57
  • 1
    Take a look at \Magento\Framework\Stdlib\DateTime\DateTime::gmtTimestamp() Feb 1, 2016 at 15:14
15

You can easily get Current Store Date Time by injecting in your class constructor in instance of \Magento\Framework\Stdlib\DateTime\TimezoneInterface and use that one to get the DateObject.

For example:

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

And then you can use it as followed:

$date = $this->timezone->formatDate();

For more information about different formats you can take a look at this article I wrote https://codeblog.experius.nl/magento-2-get-current-store-date-time/

3
  • 1
    What if i want to get timeZone ?? Sep 7, 2017 at 7:37
  • one can get timezone using this code $this->storeManager->getStore()->getConfig('general/locale/timezone'). and the dependency class for this would be \Magento\Store\Model\StoreManagerInterface $storeManager, Sep 20, 2019 at 15:51
  • @Mr. Lewis, this returns only the date. How do I get the time too? May 14, 2020 at 6:20
7

Magento 2.x have context objects for different classes, if you are in a context of Block then context object can give you locale date object as follows:

/**
 * Locale Date/Timezone
 * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
 */
protected $_timezone;

/**
 * @param \Magento\Catalog\Block\Product\Context $context
 * @param array $data
 */
public function __construct(
    \Magento\Catalog\Block\Product\Context $context,
    array $data = []
) {
    $this->_timezone = $context->getLocaleDate();
    parent::__construct(
        $context,
        $data
    );
}

then you can use it like following:

$todayDate = $this->_timezone->date()->format('Y-m-d H:i:s');

This will avoid errors while executing di:compile command.

6

To get the current date time of a particular store (other than current store in StoreManager):

Reference from \Magento\Framework\Stdlib\DateTime\Timezone::convertConfigTimeToUtc()

/** @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone */
/** @var \Magento\Framework\Stdlib\DateTime\Timezone $timezone */

$timezone = $this->timezone->getConfigTimezone(\Magento\Store\Model\ScopeInterface::SCOPE_STORES, $storeId);
$currentDate = new \DateTime('now', new \DateTimeZone($timezone));
var_dump($currentDate->format('Y-m-d H:i:s'));

\Magento\Framework\Stdlib\DateTime will get you UTC date time, GMT date time or current store's date time.

Magento 2 sets UTC in app/bootstrap:

date_default_timezone_set('UTC');

\DateTime uses this PHP timezone setting by default. Magento 2 will use internally UTC and it saves in MySQL in UTC also. Linux servers and MySQL servers usually are set to UTC timezone. The chain of the timezone settings on a server is not in scope of this topic.

Magento 2 will display on frontend the date in current store's timezone using locale resolver \Magento\Framework\Locale\Resolver to get the current store timezone (e.g Europe/Bruxelles).

3

We can set store timezone using observer with event "controller_action_predispatch"

Create events.xml in Mymodle/etc/frontend/events.xml folder

<?xml version="1.0" encoding="UTF-8"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch">
        <observer name="mymodule_timezone_set" instance="MyNamespace\Mymodule\Observer\SetStoreTimezoneObserver" />
    </event> </config>

In Observer folder create file SetStoreTimezoneObserver.php

<?php
namespace MyNamespace\Mymodule\Observer;

use Magento\Framework\Event\ObserverInterface;

class SetStoreTimezoneObserver implements ObserverInterface
{

    protected $_storeTime;
    protected $_storeManager;

    public function __construct(
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    )
    {
        $this->_storeTime = $timezone;
        $this->_storeManager = $storeManager;
        $this->setStoreTimezone();
    }

    /**
     * Retrieve store model instance
     *
     * @return \Magento\Store\Model\Store
     */
    public function getStore()
    {
        return $this->_storeManager->getStore();
    }

    /*
     * Set Store Timezone
     */
    public function setStoreTimezone()
    {
        date_default_timezone_set(
            $this->_storeTime->getConfigTimezone('store', $this->getStore())
        );
    }

    /**
     * Predispath admin action controller
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $this->setStoreTimezone();
    }
}

Now instead of getting "UTC" date, we get current store date using simple date("Y-m-d H:i:s") function.

2

In my case, if i use this on my controller, it doesn't work. I get the default locale date instead.

But if i use it on my block it works.

\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone
$todayDate = $this->_timezone->date()->format('Y-m-d H:i:s');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.