4

I am using php function now() to set current date and time.But getting an error.

So please help me how can I set current date time in magento 2.

0

2 Answers 2

4

protected $_dateFactory;

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

then write this to get current date

$date = $this->_dateFactory->create()->gmtDate();

2

For getting current date time ,you should use dateDateTime Factory class's function date().

use $this->_dateFactory->create()->date() for set current date.

First,you need to inject Magento\Framework\Stdlib\DateTime\DateTimeFactory at your __construct() function.Then by calling date() function ,you will get current date. This function ability to Converts input date into date with timezone offset

 public function __construct(
...
        \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateFactory,
.....
    ) {
    ...
         $this->_dateFactory = $dateFactory;
    ....       
        parent::__construct(
        ...
        );
    }

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.