Back to Top

Save and Get Date Time According To Time Zone In Magento2

Updated 20 February 2024

Here we will learn how to Save and Get Date Time According To Time Zone In Magento2

1# For get Date Time according Time Zone in magento2

<?php
namespace Webkul\TimeZone\Helper;
/**
 * Webkul data helper
 * @category    Webkul
 */
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var Magento\Framework\Stdlib\DateTime\TimezoneInterface
    */
    protected $_timezoneInterface;

    /**
    * @param \Magento\Framework\App\Helper\Context $context
    * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface
    */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        //time zone interface 
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezoneInterface
    ) 
    {
        $this->_timezoneInterface = $timezoneInterface;
        parent::__construct($context);
    }

    /**
     * @param string $dateTime
     * @return string $dateTime as time zone
    */
    public function getTimeAccordingToTimeZone($dateTime)
    {
        // for get current time according to time zone
        $today = $this->_timezoneInterface->date()->format('m/d/y H:i:s');

        // for convert date time according to magento time zone
        $dateTimeAsTimeZone = $this->_timezoneInterface
                                        ->date(new \DateTime($dateTime))
                                        ->format('m/d/y H:i:s');
        return $dateTimeAsTimeZone;
    }
}

i define this in helper file you can define it as your requirement

2# Save Date Time in magento2

There are two type of time zone one is Default Time zone and another is Config Timezone

when we save any date in database system spect datetime is in default timezone but actually that datetime is in current time zone of user so before save we’ll convert datetime in dafault timezone of system.

<?php
/**
 * Webkul TimeZone Save Controller
 *
 * @category    Webkul
 * @package     Webkul_TimeZone
 * @author      Webkul Software Private Limited
 *
 */
namespace Webkul\TimeZone\Controller\Adminhtml\TimeZone;


class Save extends \Magento\Backend\App\Action
{
    /**
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        if (!$data) {
            $this->_redirect('timezone/timezone/index');
            return;
        }
        try {
            $timeZoneObj = $this->_objectManager->create('Webkul\TimeZone\Model\TimeZone');

            // Magento Timezone Interface
            $timezone =$this->_objectManager->create('Magento\Framework\Stdlib\DateTime\TimezoneInterface');

            // function converToTz use for conver user timezone date in default timezone(UTC)
            // converToTz is not magento native method 
            $data['publish_datetime'] = $this->converToTz(
                $data['publish_datetime'], 
                // get default timezone of system (UTC)
                $timezone->getDefaultTimezone(), 
                // get Config Timezone of current user 
                $timezone->getConfigTimezone()
            );
            $timeZoneObj->setData($data);
            $timeZoneObj->setPublishDatetime($data['publish_datetime']);
            $timeZoneObj->save();
            $this->messageManager->addSuccess(__('Timezone has been successfully saved.'));
        } catch (Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        $this->_redirect('timezone/timezone/index');
    }

    /**
     * converToTz convert Datetime from one zone to another
     * @param string $dateTime which we want to convert
     * @param string $toTz timezone in which we want to convert
     * @param string $fromTz timezone from which we want to convert
    */
    protected function converToTz($dateTime="", $toTz='', $fromTz='')
    {   
        // timezone by php friendly values
        $date = new \DateTime($dateTime, new \DateTimeZone($fromTz));
        $date->setTimezone(new \DateTimeZone($toTz));
        $dateTime = $date->format('m/d/Y H:i:s');
        return $dateTime;
    }

    /**
     * Check Timezone save permission.
     *
     * @return bool
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Webkul_Timezone::add');
    }
}

using this process you can save/get datetime in database according to timezone
Thanks 🙂

Searching for an experienced
Magento Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


2 comments

  • Raj
    • Suraj Kumar (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home