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.


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

  • 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 Dec 1 '16 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. – Miroslav Petroff Dec 1 '16 at 8:00
  • Yes it worked. Thank you very much for your time – chin Dec 1 '16 at 9:25

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.