Set the Date Format in Magento 2

Sometimes store owner need to change the date format according to their target audience. Every country does not follow the same date and time format. So, we can convert a date to any other locale according to our need.

 

To change visible date format in date inputs You need to set proper Interface Locale in the Account Setting.

I’ve come up with two methods to set date format in Magento 2, as described below:

 

From the Admin Panel:

  1) Login to the admin panel

  2) Go to Stores -> Configuration

  3) Expand the Catalog option and choose the catalog option

  4) Expand Date & Time Custom Options

           a) Use JavaScript Calendar – Set to “Yes” if you want to use the popup calendar for date fields.

           b) Date Fields Order – Set this field according to the format you require. For example, MM/DD/YY or DD/MM/YY

           c) Time Format – Choose the 12-hour format or the 24-hour format from the dropdown

           d) Year Range – Enter the year to set the from and to dates for the year range in the dropdown.

               If this field is left blank, it takes the default value as the   current year.

5) Save configuration

 

This should give you the result your after. you may need to redeploy your website. Also you may need to flush the cache.

 

With the help of Programmatically:

You can set Custom formatting of Date using Magento 2 by DateTimeFactory Class. You just need to pass custom format of date in gmtDate() function as per your requirement.

<?php
namespace Vendor\Extension\Model;
use Magento\Framework\Stdlib\DateTime\DateTimeFactory;
class ChangeDate
{
    private $dateTimeFactory;
    public function __construct(
        DateTimeFactory $dateTimeFactory
    ) {
        $this->dateTimeFactory = $dateTimeFactory;
    }
    public function getDateByFormat($format)
    {
        $dateModel = $this->dateTimeFactory->create();
        return $dateModel->gmtDate($format);
    }
}

OR

<?php
namespace Vendor\Extension\Model;

use Magento\Framework\Stdlib\DateTime\DateTimeFactory;

class FormatDate
{
    /**
     * Custom Date format
     */
    const FORMAT_DATE = 'd-m-Y H:i:s';

    /**
     * @var DateTimeFactory
     */
    private $dateTimeFactory;

    public function __construct(
        DateTimeFactory $dateTimeFactory
    ) {
        $this->dateTimeFactory = $dateTimeFactory;
    }

    /**
     * Get Current Format date
     *
     * @return string
     */
    public function getFormatDate(): string
    {
        $dateModel = $this->dateTimeFactory->create();
        return $dateModel->gmtDate(self::FORMAT_DATE);
    }
}

In the above date format result format will be, “d-m-Y H:i:s”. Its Indian standard date format like Date-Month and Year.

Call $this->getFormatDate() to get Result as specified Date format of current time.

You just need to change the format using const FORMAT_DATE.

Hope so it will help.