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.
AI-Powered Recommended Articles
How to Add Date and Time Picker on Store Configuration in Magento 2
Add a date and time picker functionality to your Magento 2 store configuration fields for more precise input.
How to Create Custom Cron Job in Magento 2
Step-by-step guide on creating custom cron jobs in Magento 2 to automate tasks and improve store performance.
How to Use Event in Magento 2
Learn how to use events in Magento 2 to trigger custom functionality and extend store operations.
How to Install Magento 2 Using Command Line
Learn how to install Magento 2 using the command line interface for a streamlined and flexible installation process.
How to Create Custom Shipping Method in Magento 2
Learn how to create and integrate a custom shipping method in Magento 2 for customized shipping options.
How to Get Order Details by Order Id in Magento 2
Learn how to retrieve detailed order information using the order ID in Magento 2 to manage customer orders efficiently.