7

I already referred Magento 2 Get Current Store Date Time

But how to use directly in .phtml file? Can able to get Date, DateTime & Also able to set it's format?

2
  • Use directly means ? you can use your template related block and render into a template (.phtml) Sep 27, 2016 at 6:41
  • @krishnaijjadaati95Dev i would not like to pass values via Block/Controller
    – Jackson
    Sep 27, 2016 at 6:47

4 Answers 4

12

You can use this in phtml file :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objDate = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
$date = $objDate->gmtDate();

But using directly object manager in phtml file is not a good practice.

5
  • It's giving Fatal error: Call to undefined method Magento\Framework\Stdlib\DateTime::gmtDate() Using Magento 2
    – Jackson
    Sep 27, 2016 at 7:06
  • Check my updated answer Sep 27, 2016 at 7:09
  • Got it. What about Format & how can i convert my Database other field's datetime in Y-m-d format??
    – Jackson
    Sep 27, 2016 at 7:10
  • You can change the date format using php date function like : date('y-m-d', strtotime($date)). or any date format as you like Sep 27, 2016 at 7:14
  • 3
    Can do with $block->formatDate($_posts->getCreatedAt()); got it. No worries Thanks :)
    – Jackson
    Sep 27, 2016 at 7:18
21
protected $_date;
 public function __construct(\Magento\Framework\Stdlib\DateTime\TimezoneInterface $date)
{
  $this->_date =  $date;
}

then use like this

$this->_date->date()->format('Y-m-d H:i:s');
0
0

Hello i am using same \Magento\Framework\Stdlib\DateTime\TimezoneInterface in my code but it displays different when i print that in file and is different in database. why?? in database i have type "updated_at timestamp"

1
  • The dateTime will be difference because TimezoneInterface is working based on the Current TimeZone already setup on the Magento and also it will update value based on UTC.. Sep 24, 2020 at 8:30
0

what if I want to give specific date here

$this->_date->date(<my-comment-date>)->format('Y-m-d H:i:s');

Your Answer

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

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