Magento, Magento 2

How to Add Days to Date in Magento 2

How to Add Days to Date in Magento 2

In this tutorial, Today I will explain how to add days to the date in Magento 2. For example, If you want to get the date for the next days or want to add 5 or 7 days to the current date then, how to add days to date and get value in Magento 2.

Let’s follow the below way to add days to date :

You may also like this :

We need to inject \Magento\Framework\Stdlib\DateTime\DateTime class into the construct and then, you can use function in your phtml or any other files :

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    protected $date;

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

    public function getNextDate()
    {
        $date = $this->date->date('Y-m-d'); // current date
        $nextdate = $this->date->date('Y-m-d', strtotime($date." +1 days")); //next day date
        return $nextdate;
    }
}

Here, we created one getNextDate() function to return the next date of the current date. You can add the number of days instead of +1 days which you want to add to the return date with additional days.

Remove generated and then, need to clean cache.

That’s it !!!

I hope this blog is easy to understand about how to add days to the date in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged ,