Magento 2 – Create Date Time Instance

datetimemagento2

How can I create Date time Instance in Magento For example 11-30-2016 5:00:00 pm.
remember this should be a datetime variable and not a string variable so that I can do Datetime operations on it.

Best Answer

You can use php Datetime object

$date = new \DateTime('now');
echo $date->format('m-d-Y h:i:s a');

Magento framework also suggests classes for doing that. You need to inject in your construct method this class

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

and then get the time with

$this->date->gmtDate();
Related Topic