Meteoff Dev
Meteoff Dev

Reputation: 57

Check if two hours are between a time range

I allow myself to ask my question here, because after several hours of trying to make my code work, it still does not work! So I would simply like to check if two times (For example 8:00 and 10:00) are included between a time range (For example between 8:00 and 9:00). I have already tried several combinations, it seems to work from time to time, but when I check if 9:00 and 10:00 is between 8:00 and 9:00, it returns that the time is not included in the time slot when it is supposed to be! Here is my code for the moment: (all data has been transformed into strtotime())

if ((($hdebut >= $ihdebutcours) && ($hdebut <= $ihfincours)) && (($hfin >= $ihdebutcours) && ($hfin >= $ihfincours))) {
    $f++;
}

For example :

Thank you very much to the people who will help me, it will help me enormously to continue my project, and sorry for my bad English! Good day to you !

Upvotes: 0

Views: 453

Answers (3)

Meteoff Dev
Meteoff Dev

Reputation: 57

I just found the problem! It was actually the operator! I changed it to "<" instead of "<="! Thank you all for your messages, and again sorry to have disturbed you! Good day to you !

($hdebut <= $ihdebutcours AND $ihdebutcours < $hfin) OR ($hdebut < $ihfincours AND $ihfincours <= $hfin)

Upvotes: 0

Anthony Meinder
Anthony Meinder

Reputation: 321

It sure is overkilled but when dealing with dates, I often go with Carbon.

With Carbon, you could easily check if a date is in the timerange of two dates

  $lessonStart = \Carbon\Carbon::parse('today at 9:00');
  $lessonEnd = \Carbon\Carbon::parse('today at 11:15');

  $arrivedAt = \Carbon\Carbon::parse('today at 9:00');
  $endedAt = \Carbon\Carbon::parse('today at 10:00');

  if ($arrivedAt->between($lessonStart, $lessonEnd) && $endedAt->between($lessonStart, $lessonEnd)) {
      //...
  }

Upvotes: 0

Simon K
Simon K

Reputation: 1523

Try PHP's DateTime...

<?php

$hdebut = '9:00';
$hfin = '11:15';
$ihdebutcours = '9:00';
$ihfincours = '10:00';

$hdebutDT = new DateTime($hdebut);
$hfinDT = new DateTime($hfin);
$ihdebutcoursDT = new DateTime($ihdebutcours );
$ihfincoursDT = new DateTime($ihfincours);

if ((($hdebutDT >= $ihdebutcoursDT) && ($hdebutDT <= $ihfincoursDT)) && (($hfinDT >= $ihdebutcoursDT) && ($hfinDT >= $ihfincoursDT))) {
    $f++;
}

You could even shorten all this by using DateTime::diff also perhaps.

Upvotes: 1

Related Questions