25

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?

43

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();
  • 1
    it gives gmt date how to get current store timezone wise date – ND17 Feb 1 '16 at 12:00
  • I have tried this but it always giving a time difference of 5 hrs can you help me – Naveenbos Mar 28 '17 at 5:25
  • How to get only time ? – Sanjay Gohil Aug 25 '17 at 6:21
  • 2
    @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 '17 at 6:34
  • How to add/subtract months into/from date by this method ? – Ajwad Syed Jul 3 at 14:22
18

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)

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

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/

  • 1
    What if i want to get timeZone ?? – Developer Webile Sep 7 '17 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, – Rajeev Singh Sep 20 at 15:51
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

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.

2

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).

0

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');
-6

Below solution is i have tried in Magento 2.1.2 CE & Works fine.

Go to file app\bootstrap.php, here end of the file u will find.

date_default_timezone_set('UTC');

Which is wrong, set to your ones

date_default_timezone_set('Asia/Singapore');

& Get Current Date Using

$magentoDateObject = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
echo $magentoDate = $magentoDateObject->gmtDate();
  • Why is date_default_timezone_set('UTC') wrong? Architecturally, it makes sense to put your default TZ to UTC, then convert between stores as you want. The same thing applies to date & times in the DB: way easier if you store them in UTC and convert on a per-need basis. – nevvermind Apr 9 '17 at 8:51
  • 1
    This is bad advice. Magento intentionally stores date/time values in the database as UTC and converts them to the store's local timezone for display to the user. – Darren Felton Aug 11 '17 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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