How to Get Current Store Date and Time in Magento 2
Developers often need to work with date and time in Magento 2. Every store has a unique time zone. Therefore, it is essential to know how the time zone works for Magento 2 stores.
For example, if your store delivers the product only after a specific time of the day, you require to get current store date and time in Magento 2 and prepare product delivery schedule according to the time.
When you save a date in Magento 2 database, it gets stored in the default time zone. But while calculating the delivery time for the above scenario, you need to convert it to the default time zone of the system to fulfil the requirement of conditional shipment like “the shipment must be done after 3 am only”.
While creating a store, you have to configure Magento 2 stores and times zones and to serve the purpose of time conversion due to the time zone differences, I’ve come up with the solution to get current store date and time in Magento 2.
Steps to Get Current Store Date and Time in Magento 2
- Create Data.php file and use this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php namespace Meetanshi\Module\Helper; use Magento\Framework\App\Helper\AbstractHelper; use Magento\Framework\App\Helper\Context; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; class Data extends AbstractHelper { protected $timezoneInterface; public function __construct(Context $context, TimezoneInterface $timezoneInterface) { $this->timezoneInterface = $timezoneInterface; parent::__construct($context); } public function getStoreDateTime() { $formatDate = $this->timezoneInterface->formatDate(); // you can also get format wise date and time $dateTime = $this->timezoneInterface->date()->format('Y-m-d H:i:s'); $date = $this->timezoneInterface->date()->format('Y-m-d'); $time = $this->timezoneInterface->date()->format('H:i'); return $dateTime; } } |
That’s all.
If you have a query regarding this post, feel free to ask in the Comment section below.
I would like to solve your query.
Do consider sharing this post with Magento Community via social media.
Thank you.
Chandresh Chauhan
He has been with Meetanshi for more than three years now as a certified Magento developer. A silent guy whom you can always find solving clients' issues, is an avid reader too.
Prev
How to Add Custom Tab View in Magento 2
How to Add Sort by “Newest Product” option in Magento 2
Next