How to set custom date format in Magento 2?
How to set custom date format in Magento 2?

How to set custom date format in Magento 2?

We can use Magento\Framework\Stdlib\DateTime\DateTimeFactory class to set custom date format.

During development, we need to set a custom date format to display in the frontend or need to pass the custom data to APIs. So here is the code to set custom date format.

namespace MagePrince\Testing\Model;

class FormatDate
{
    private $dateTimeFactory;

    public function __construct(
        \Magento\Framework\Stdlib\DateTime\DateTimeFactory $dateTimeFactory
    ) {
        $this->dateTimeFactory = $dateTimeFactory;
    }

    public function getFormatDate()
    {
        $dateModel = $this->dateTimeFactory->create();
        return $dateModel->gmtDate('d-m-Y H:i:s');
    }
}

Now you can use the $this->getFormatDate() to get the formatted date.

Here are all the date formats which you can use for format the date

$dateModel->gmtDate("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$dateModel->gmtDate("m.d.y");                         // 03.10.01
$dateModel->gmtDate("j, n, Y");                       // 10, 3, 2001
$dateModel->gmtDate("Ymd");                           // 20010310
$dateModel->gmtDate('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$dateModel->gmtDate('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$dateModel->gmtDate("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$dateModel->gmtDate('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$dateModel->gmtDate("H:i:s");                         // 17:16:18
$dateModel->gmtDate("Y-m-d H:i:s");                   // 2001-03-10 17:16:18

You can use the predefined function of Magento\Framework\Stdlib\DateTime\DateTimeFactory class like:

/**
 * Calculates timezone offset
 *
 * @param  string|null $timezone
 * @return int offset between timezone and gmt
 */
public function calculateOffset($timezone = null)

/**
 * Forms GMT date
 *
 * @param  string $format
 * @param  int|string $input date in current timezone
 * @return string
 */
public function gmtDate($format = null, $input = null)

/**
 * Converts input date into date with timezone offset
 * Input date must be in GMT timezone
 *
 * @param  string $format
 * @param  int|string $input date in GMT timezone
 * @return string
 */
public function date($format = null, $input = null)

/**
 * Forms GMT timestamp
 *
 * @param  int|string|\DateTimeInterface $input date in current timezone
 * @return int
 */
public function gmtTimestamp($input = null)

/**
 * Converts input date into timestamp with timezone offset
 * Input date must be in GMT timezone
 *
 * @param  int|string $input date in GMT timezone
 * @return int
 */
public function timestamp($input = null)

/**
 * Get current timezone offset in seconds/minutes/hours
 *
 * @param  string $type
 * @return int
 */
public function getGmtOffset($type = 'seconds')