How to Convert Date and Time Based on Timezone in Magento 2

As we all know in Magento 2 when we save date and time by default Magento will save in Local time. But, when we get the date and time it'll provide time based Universal timezone. So, in that case, if you want to get the date & time according to your config timezone then you are in a right place. In this article, We're going to explain to you How to Get Date and Time Based on Timezone in Magento 2.

Let's get started!!

Before we start make sure you have set your desired Timezone in Following Configuration..

Store > Configuration > General > General > Locale Options > Timezone

Now, you need to add TimezoneInterface dependency in your class file like the below code.

saveCopyzoom_out_map
<?php namespace Devhooks\HelloWorld\Block; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; class YourClassName extends Template { public function __construct( ... TimezoneInterface $timezoneInterface ... ) { ... $this->timezoneInterface = $timezoneInterface; ... } public function getDateTime($date) { return $this->timezoneInterface->date(new \DateTime($date))->format('m/d/y H:i:s'); } }

In the above code, you can see, that we've created getDateTime function in our class and get Date and Time according to the configuration timezone using TimezoneInterface.

That's it.

We hope this Magento technicle guide helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions or doubts.

P.S. Do share this post with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off