Date and time is essential element for any business to keep track of their data over a different time frame. But when it comes to any CMS or platform, it does provide the functionality to fetch date and time using its default variable without a single line of code and the same thing applied to Magento 2. By default, you can set system date and time using its backend system configuration that you want to use in Magento 2. So, whenever you fetch date and time it uses its default type as shown below.
But while custom development, many times it happens that you have to fetch date and time in a specific format. Also, Magento 2 is not providing an option to fetch date in a different format. So, you have to manually code for it.
To do the same first you need to create an “Index.php” file using the following code at the below path.
<pre class="lang:default decode:true">
class Index extends \Magento\Framework\App\Action\Action
const FORMAT_DATE = 'd-m-Y H:i:s';//set format as per your requirement
public function __construct(
$this->dateTimeFactory = $dateTimeFactory;
public function getCurrentDate()
$dateModel = $this->dateTimeFactory->create();
public function execute()
echo "Current Date : ".$this->getCurrentDate();
That’s it. You are free to manipulate this code according to your needs.
Lastly, if you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends and Let us know if you are facing any issue while implementing this code.