z0mbieKale
z0mbieKale

Reputation: 1028

How to calculate hour intervals from two datetimes in PHP?

I am creating an online booking system. when user clicks on a date in calendar, it returns two datetimes (start and end) for that date. I am trying to calculate all the hours from start to end which I was able to do, but I need to display the hours in intervals.

Lets say user has added available time tomorrow from 10.00-14.00 then I need to display the times like this:

10.00-11.00

11.00-12.00

12.00-13.00

13.00-14.00

for the specific day.

What I have so far.

public function getTimes()
{

  $user_id = Input::get("id"); //get the user id
  $selectedDay = Input::get('selectedDay');   // We get the data from AJAX for the day selected, then we get all available times for that day
  $availableTimes = Nanny_availability::where('user_id', $user_id)->get();

  // We will now create an array of all booking datetimes that belong to the selected day
  // WE WILL NOT filter this in the query because we want to maintain compatibility with every database (ideally)

  // For each available time...
  foreach($availableTimes as $t => $value) {
    $startTime = new DateTime($value->booking_datetime);

    if ($startTime->format("Y-m-d") == $selectedDay) {
      $endTime = new DateTime($value->booking_datetime);

      date_add($endTime, DateInterval::createFromDateString('3600 seconds'));

      // Try to grab any appointments between the start time and end time
      $result = Nanny_bookings::timeBetween($startTime->format("Y-m-d H:i"), $endTime->format("Y-m-d H:i"));

      // If no records are returned, the time is okay, if not, we must remove it from the array
      if($result->first()) {
        unset($availableTimes[$t]);
      }

    } else {
      unset($availableTimes[$t]);
    }
  }

  return response()->json($availableTimes);
}

How can I get the intervals?

Upvotes: 1

Views: 111

Answers (1)

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Assuming the hour difference between start and end is 1 as per your question, you could use DateInterval and DatePeriod, to iterate over the times like:

$startDate = new DateTime( '2017-07-18 10:15:00' );
$endDate = new DateTime( '2017-07-18 14:15:00' );
$interval = new DateInterval('PT1H'); //interval of 1 hour
$daterange = new DatePeriod($startDate, $interval ,$endDate);

$times = [];
foreach($daterange as $date){
    $times[] = $date->format("H:i") . " -- " 
        . $date->add(new DateInterval("PT1H"))->format("H:i");
}
echo "<pre>"; print_r($times);
//gives
Array
(
    [0] => 10:15 -- 11:15
    [1] => 11:15 -- 12:15
    [2] => 12:15 -- 13:15
    [3] => 13:15 -- 14:15
)

Update

You could use json_encode() in order to return the json times data, as:

$jsonTimes = json_encode($times);

Upvotes: 4

Related Questions