DEV Community

Anuradha Fernando
Anuradha Fernando

Posted on

Get nearest time slot in the past (in Magento2)

Let's assume that you have a list of Time Slots generated within the 30 minutes intervals. You need to get the closest time slot in the past based on the current server time.

eg:
Start Time: 14:00
End Time: 18:00
Interval: 30 (minutes)

Output:

14:00
14:30
15:00
15:30
16:00
16:30
17:00
17:30
18:00
Enter fullscreen mode Exit fullscreen mode

Current time: 17:26 (you can get the current server time from the Magento DateTimeFactory)

So the output will be 17:00.
Why? because we have 30minutes intervals in our time list. Therefore according to the current time 17:26 the previous closest time slot is 17:00

How to get the current Date/Time from Magento core

use \Magento\Framework\Stdlib\DateTime\DateTimeFactory;

/**
 * @var DateTimeFactory
*/
protected $dateTimeFactory;

public function __construct(
    DateTimeFactory $dateTimeFactory
)
{
    $this->dateTimeFactory = $dateTimeFactory;
}

public function getClosestTimeSlot()
{
    $dateModel = $this->dateTimeFactory->create();
    $currTime = date('H:i', strtotime($dateModel->gmtDate()));

    $openingTime = '14:00';
    $closingTime = '18:00';
    $interval = 30; //in minutes

    $timeSlots = [];
    //set the intervals based on the $timeSlotLength
    $nextInterval = '+' . $interval . 'minutes';

    $strOpeningTime = strtotime($openingTime);
    $strClosingTime = strtotime($closingTime);

    while ($strOpeningTime <= $strClosingTime) {
       array_push($timeSlots, date('H:i', 
       $strOpeningTime));
       $strOpeningTime = strtotime($nextInterval, $strOpeningTime);
    }  

    //sets the array to be returned with the lowest time slot 
      from time slot array
    $timeArray = [
        'lower '=> min(current($timeSlots), $currTime)
    ];

    //store the closest lower time slot to the $timeArray
    foreach ($timeSlots as $ts) {
        if ($currTime > $ts)
            $timeArray['lower'] = $ts;
    }

    return $timeArray['lower']; //output will be 17:00
}

Enter fullscreen mode Exit fullscreen mode

cheers!!

Top comments (0)