3

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.

2 Answers 2

2

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();
3
  • Thank you so much for your time. But I need to do something like new DateTime("2016-11-30 20:26:26")). This is working in phtml file but not in helper or block.
    – chin
    Commented Dec 1, 2016 at 3:52
  • why it's not working on helper or block? Give more details. I think that you can combine both objects and get what you want. I've used magento framework datetime object in models and it's working perfect. I don't think that this is not working for blocks or helpers. Commented Dec 1, 2016 at 8:00
  • Yes it worked. Thank you very much for your time
    – chin
    Commented Dec 1, 2016 at 9:25
0

Just to provide an alternative - the \Magento\Framework\Stdlib\DateTime\TimezoneInterface class provides support for more customizable options like locale, timezone, output formats, etc.

Your Answer

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

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