How to set custom date format using Magento 2?

You can set Custom formatting of Date using Magento 2 by DateTimeFactory Class.

You just need to pass the custom format of the date in the gmtDate() function as per your requirement.

Many times, you need to set the Date format to a specific format, While you are working with third-party API you need to pass the Date as the specific format from Magento, in this situation you can use below code snippet below.


namespace Rbj\CustomDate\Model;

use Magento\Framework\Stdlib\DateTime\DateTimeFactory;

class FormatDate
    public const FORMAT_DATE = 'd-m-Y H:i:s';

    private DateTimeFactory $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 formats like Date-Month and Year.

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

You just need to change the format using const FORMAT_DATE.