Adding/Remove 1 Hour from a line that references date (PHP)
-
16-04-2021 - |
Question
I'm attempting to debug a Timezone issue in a custom Magento module. One of the tests I would like to try is to ADD/REMOVE 1hr from whatever is output from this line of code.
I suspect ADDING 1hr could be as simple as implementing a "+1" somehow. And perhaps REMOVING 1hr might involve going back 1 Day and forward 23 hours. But honestly, I don't know what to start with this.
Line
$estimatedDeliveryDate = $this->localeDate->date()->setTime(0,0,0);
Context
class Estimator
{
private $localeDate;
public function __construct(
\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
) {
$this->localeDate = $localeDate;
}
public function addEstimatedDeliveryDate(&$items)
{
$now = $this->localeDate->date();
$todayDate = $this->localeDate->date();
foreach ($items as &$item) {
$estimatedDeliveryDate = $this->localeDate->date()->setTime(0,0,0);
...
No correct solution
OTHER TIPS
With the help of code below, I' able to add number of days/hours to current date and time.
<?php
namespace Namespace\Modulename\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
class Data extends AbstractHelper
{
/**
* @var TimezoneInterface
*/
protected $_timezoneInterface;
/**
* Data constructor.
* @param Context $context
* @param TimezoneInterface $timezoneInterface
*/
public function __construct(
Context $context,
TimezoneInterface $timezoneInterface
)
{
parent::__construct($context);
$this->_timezoneInterface = $timezoneInterface;
}
/**
* @return string
*/
public function getOrderScheduledAt(): string
{
$x = '2'; // Number of days to be added (same way you can use 'hours')
$currentDateTime = $this->_timezoneInterface->date()->format('d-m-Y H:i:s');
return $this->_timezoneInterface->date(strtotime($currentDateTime." +{$x} days"))->format('d-m-Y H:i:s');
}
}
In the same way, you can use $this->_timezoneInterface->date(strtotime($currentDateTime." +1 days"))->format('d-m-Y H:i:s');
to add one hour.
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange