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.

3

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

| improve this answer | |
1

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(
        ...
        );
    }
| improve this answer | |

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.