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.
- How to Add Image Uploader on Store Configuration in Magento 2
- How to Add Custom Select/MultiSelect Options on Store Configuration in Magento 2
- How to Add Dynamic Row on Store Configuration in Magento 2
- How to Add Date & time Picker on Store Configuration in Magento 2
- How to Add Link on Store Configuration Fields Comment in Magento 2
- How to Use Javascript Mixins in Magento 2
- How to Add Custom Validation Rule in Magento 2
- How to Get Product Collection
- How to Setup Magento 2 PWA Studio
- How to Get Current Category
- How to Get Current Product
- Get Product Collection with Filters
- How to Create And Use Plugin In Magento 2