Home > Software engineering >  PHP DateTime how much is in interval of 2 other dates?
PHP DateTime how much is in interval of 2 other dates?

Time:08-24

I am having difficulties seeing "how much" of 2 DateTime's are between 2 other date times.

For instance, i have a "start" and "end" datetime (i omit the day, seeing as only the time is relevant here):

Start: 01:00
End: 09:30

And i have 2 other times:

Night_start: 00:00
Night_end: 04:00

So, i need to figure out "how much" of the "start" and "end" are between the "night_start" and "night_end" part.

The correct answer is obviously 3 hours, but how would i go about calculating this?

Hope my question makes sense. thanks.

CodePudding user response:

So you're given 4 values and want to find the overlap.

sort them into order.

If the second value of the four is the last value of either of the input pairs the ranges do not overlap, else the overlap is the middle two values,

subtract to find the length of the overlap.

anoither way

given (as,ae),(bs,be) the overlap is

min(ae,be) - max(as,bs) when that result is positive, or no overlap for zero or negative.

you will need comparison and difference algorithms to work with your data types.

CodePudding user response:

With min(ae,be) - max(as,bs), and a time to decimal function. Something like that, then?

<?php
$start_date = '01:00:00';
$end_date = ' 09:30:00';
$start_night = '00:00:00';
$end_night = '04:00:00';

function timeToDecimal($time)
{
    $hms = explode(":", $time);
    return ($hms[0]   ($hms[1]/60)   ($hms[2]/3600));
}

$min = min(timeToDecimal($end_date), timeToDecimal($end_night));
$max = max(timeToDecimal($start_date), timeToDecimal($start_night));
$result = ($min-$max>0) ? $min-$max : timeToDecimal($end_night)-timeToDecimal($start_night);

echo  $result.' hour(s) of night';

Results:

3 hour(s) of night
  • Related