3

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?

  • Use directly means ? you can use your template related block and render into a template (.phtml) – Krishna ijjada Sep 27 '16 at 6:41
  • @krishnaijjadaati95Dev i would not like to pass values via Block/Controller – Ankit Shah Sep 27 '16 at 6:47
10

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.

  • It's giving Fatal error: Call to undefined method Magento\Framework\Stdlib\DateTime::gmtDate() Using Magento 2 – Ankit Shah Sep 27 '16 at 7:06
  • Check my updated answer – Ashish Jagnani Sep 27 '16 at 7:09
  • Got it. What about Format & how can i convert my Database other field's datetime in Y-m-d format?? – Ankit Shah Sep 27 '16 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 – Ashish Jagnani Sep 27 '16 at 7:14
  • 2
    Can do with $block->formatDate($_posts->getCreatedAt()); got it. No worries Thanks :) – Ankit Shah Sep 27 '16 at 7:18
8
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');
  • Thanks @ManiMaran A it worked for me. – Ankita Biswas Jul 17 at 9:36

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.