Magento 2 Get Current Store Date Time

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();

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)


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/

Tags:

Date

Magento2