How to get current date time programmatically in Magento 2?

Magento 2 Fetch Current Date Time programmatically by use of the DateTime() method.

If you want to fetch the GMT Date time Check the link, Magento 2 GMT date time Format.

Just use the given code to display the current date and time from the system.

public function _getCurrentDateTime(): string
    return (new \DateTime())->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT);

2023-04-05 11:24:58

In the above, method we have used DATETIME_PHP_FORMAT which uses a date-time format like ‘Y-m-d H:i:s’

You can also use the alternate Date format from Magento\Framework\Stdlib\DateTime class,

public const DATETIME_INTERNAL_FORMAT = 'yyyy-MM-dd HH:mm:ss';

public const DATE_INTERNAL_FORMAT = 'yyyy-MM-dd';

public const DATETIME_PHP_FORMAT = 'Y-m-d H:i:s';

public const DATE_PHP_FORMAT = 'Y-m-d';

You can use any Date format as per your requirement.