PHP: временной интервал, сколько времени утром и ночью?

Предположим, у меня есть две строки, такие как «08:50» (начало) и «23:50» (конец).
Теперь я знаю, что утро с 06:00 до 22:00, а ночь с 22:00 до 06:00.

Вопрос в том, как я могу узнать, сколько времени утром и сколько ночью? Это должно быть 9 часов утром и 1 час 50 минут ночью.

Я сделал код, но иногда (с определенными значениями) он падает, и он теряет пару минут:

function analizza_mattina_sera($result2)
{
$inizio_giorno = oreToMinuti("06:00");
$fine_giorno = oreToMinuti("22:00");
$inizio_notte = oreToMinuti("22:00");
$fine_notte = oreToMinuti("06:00");
$conto_minuti_giorno = "";
$conto_minuti_notte = "";

while ($row2 = mysql_fetch_array($result2)) {

$data1 = strtotime($row2["anno"]
."-". $row2["mese"]
."-". $row2["giorno"]
." ". $row2["ora_effettiva"]);

$data2 = strtotime($row2["anno"]
."-". $row2["mese"]
."-". $row2["giorno"]
." ". $row2["ora_teorica"]);

$differenza = (($data2 - $data1) / 3600) / (1 / 60);

if ($row2["verso"] == "entrata") {
$ora_usa = $row2["ora_effettiva"];
if (oreToMinuti($ora_usa) < $inizio_giorno) {
$conto_minuti_notte = $fine_notte - oreToMinuti($ora_usa);
}
if (oreToMinuti($ora_usa) > $inizio_giorno) {
$conto_minuti_giorno = oreToMinuti($ora_usa) - $inizio_giorno;
}
}
else {
$ora_usa = $row2["ora_effettiva"];
if (oreToMinuti($ora_usa) < $fine_giorno) {
if (oreToMinuti($ora_usa) < $fine_notte) {
$conto_minuti_notte = ($fine_notte - oreToMinuti($ora_usa)) - $conto_minuti_notte;
}
else {
$conto_minuti_giorno = oreToMinuti($ora_usa) - $inizio_giorno - $conto_minuti_giorno;
}
}
else {
$conto_minuti_notte = oreToMinuti($ora_usa) - $inizio_notte;
$conto_minuti_giorno = $fine_giorno - $conto_minuti_giorno - $inizio_giorno;
}
}
}

return str_replace("-", "", ($conto_minuti_giorno == "" ? 0 : $conto_minuti_giorno)
."_". ($conto_minuti_notte == "" ? 0 : $conto_minuti_notte)) ."<br />";
}

2

Решение

Вы можете попробовать это (вы должны добавить некоторую проверку).

Вот как это использовать, он будет возвращать массив утренних периодов в минутах и ​​ночных периодов в минутах:

categorizePeriod('08:50', '23:50');

Вот функции:

function minutesDiff($startTime, $endTime)
{
$isNextDay = ($startTime > $endTime) ? 1 : 0;
$start = explode(':', $startTime);
$end = explode(':', $endTime);
$diffInSeconds = abs(mktime($start[0], $start[1], 0, null, date('j'), null) - mktime($end[0], $end[1], 0, null, date('j') + $isNextDay, null));

return floor($diffInSeconds/60);
}

function inMorning($time, array $morning)
{
return ($morning[0] <= $time && $time <= $morning[1]);
}

function categorizePeriod($startTime, $endTime, array $morning = array('06:00', '22:00'))
{
if ($startTime == $endTime) {
return array(0, 0);
} else if ($startTime > $endTime) {
$beforeMidnight = categorizePeriod($startTime, '23:59', $morning);
$afterMidnight = categorizePeriod('00:00', $endTime, $morning);

return array(
$beforeMidnight[0] + $afterMidnight[0] + (int)inMorning('00:00', $morning),
$beforeMidnight[1] + $afterMidnight[1] + (int)!inMorning('00:00', $morning),
);
}

if (inMorning($startTime, $morning) && inMorning($endTime, $morning)) {
return array(
minutesDiff($startTime, $endTime),
0
);
} elseif (!inMorning($startTime, $morning) && !inMorning($endTime, $morning)) {
return array(
0,
minutesDiff($startTime, $endTime)
);
} elseif (inMorning($startTime, $morning) && !inMorning($endTime, $morning)) {
return array(
minutesDiff($startTime, $morning[1]),
minutesDiff($morning[1], $endTime)
);
} elseif (!inMorning($startTime, $morning) && inMorning($endTime, $morning)) {
return array(
minutesDiff($morning[0], $endTime),
minutesDiff($startTime, $morning[0])
);
}
}
2

Другие решения

Я надеюсь, что это то, что вы ищете .. Я перевел в часы ..

Скажем, например

Start - 4.30 and End - 21.30 then morning 15.5 hours and night 1.5 hours
Start - 4.30 and End - 22.30 then morning 16 hours and night 2 hours
Start - 6.30 and End - 21.30 then morning 15 hours and night 0 hours
Start - 6.30 and End - 22.30 then morning 15.5 hours and night 0.5 hours

Ниже приводится сценарий, который может быть полезен для вас.

        <?php
//Get the timeslote how many hours spent in the morning and how many hours spent in the night
$start = "00:00";
$end = "00:00";
$morningSlote = "06:00 - 22:00";
$nightSlote = "22:00 - 06:00";
$startTime = strtotime($start);
$endTime = strtotime($end);
$startDate = date("m/d/Y");
$endDate = date("m/d/Y");
if($startTime > $endTime) {
//Date will be changed
//i.e. 11.30 PM - 2.30 AM
//i.e. 11.30 PM - 6.20 PM
$startDate = date("m/d/Y H:i:s",strtotime($start));
$endDate = date("m/d/Y H:i:s",strtotime("+1 day".$end));
} else if($endTime > $startTime) {
//No date will be changed
//i.e. 2.30 AM - 11.30 PM
//i.e. 2.30 AM - 6.30 AM
$startDate = date("m/d/Y H:i:s",strtotime($start));
$endDate = date("m/d/Y H:i:s",strtotime($end));
}
$output = getCorrectTimeslote($startDate, $endDate, $morningSlote, $nightSlote);

echo "<br>spent in the morning: ".$output["morningSession"]." Hours";
echo "<br>spent in the night: ".$output["nightSession"]." Hours";


function getCorrectTimeslote($startDate, $endDate, $morningSlote, $nightSlote) {
$output = array();
$morningSloteStart = "";
$morningSloteEnd = "";
$nightSloteStart = "";
$nightSloteEnd = "";

$morningSloteExplodedResult = array();
if(strpos($morningSlote,"-") !== false) {
$morningSloteExplodedResult = explode("-",$morningSlote);
$morningSloteStart = date("m/d/Y H:i:s",strtotime(trim($morningSloteExplodedResult[0])));
$morningSloteEnd = date("m/d/Y H:i:s",strtotime(trim($morningSloteExplodedResult[1])));
}

$nightSloteExplodedResult = array();
if(strpos($nightSlote,"-") !== false) {
$nightSloteExplodedResult = explode("-",$nightSlote);
$nightSloteStart = date("m/d/Y H:i:s",strtotime(trim($nightSloteExplodedResult[0])));
$nightSloteEnd = date("m/d/Y H:i:s",strtotime("+1 day".trim($nightSloteExplodedResult[1])));
}

if((isset($morningSloteStart) && !empty($morningSloteStart)) && (isset($morningSloteEnd) && !empty($morningSloteEnd)) && (isset($nightSloteStart) && !empty($nightSloteStart)) && (isset($nightSloteEnd) && !empty($nightSloteEnd))) {

$morningSession = 0;
$nightSession = 0;
if($endDate >= $startDate) {
if($morningSloteStart >= $startDate) {
//No date will be changed
if($endDate > $nightSloteStart) {
//i.e. 2.30 AM - 11.30 PM
if($morningSloteStart > $startDate) {
$nightSession = ago($morningSloteStart,$startDate);
}
$morningSession = ago($morningSloteEnd,$morningSloteStart);
$nightSession += ago($endDate,$nightSloteStart);
} else if($endDate >= $morningSloteStart) {
//i.e. 2.30 AM - 6.30 AM
//i.e. 2.30 AM - 6.30 AM
$nightSession = ago($morningSloteStart,$startDate);
$morningSession = ago($endDate,$morningSloteStart);
} else {
$morningSession = 0;
$nightSession = ago($endDate,$startDate);
}
} else if($endDate >= $nightSloteEnd) {

//Date will be changed
if($morningSloteStart < $startDate && $endDate < $nightSloteStart) {
//23:30 - 22:30
$morningSloteStart = date("m/d/Y H:i:s", strtotime("+1 day".$morningSloteStart));
$morningSloteEnd = date("m/d/Y H:i:s", strtotime("+1 day".$morningSloteEnd));
$nightSloteStart = date("m/d/Y H:i:s", strtotime("+1 day".$nightSloteStart));
$nightSession = ago($morningSloteStart,$startDate);
$morningSession = ago($morningSloteStart,$morningSloteEnd);
$nightSession += ago($endDate,$nightSloteStart);
} else {
//Removing date addition
$endDate = date("m/d/Y H:i:s", strtotime("-1 day".$endDate));
//i.e. 11.30 PM - 6.00 AM && 6.00 AM - 6.20 PM
$nightSession = ago($startDate,$nightSloteEnd);
$morningSession = ago($endDate,$morningSloteStart);
}
} else {
if($startDate >= $morningSloteStart && $nightSloteStart >= $endDate) {
//i.e. 6.30 AM - 9.30 AM
$nightSession = 0;
$morningSession = ago($endDate,$startDate);
} else if($startDate >= $morningSloteStart && $nightSloteStart < $startDate) {
//i.e. 22.30 PM - 23.59
$nightSession = ago($startDate,$endDate);
$morningSession = 0;
} else if($startDate >= $morningSloteStart && $nightSloteStart < $endDate) {

//i.e. 5.30 PM - 23.59
$nightSession = ago($nightSloteStart,$endDate);
$morningSession = ago($startDate,$nightSloteStart);
} else {
//Date will be changed
//i.e. 11.30 PM - 6.00 AM && 6.00 AM - 2.30 AM
$morningSession = 0;
$nightSession = ago($endDate,$startDate);
}
}
}

}

$output["morningSession"] = $morningSession/60; //hours
$output["nightSession"] = $nightSession/60; //hours
return $output;
}


function ago($datetime1,$datetime2) {
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime2);
$interval = $date1->diff($date2);
$minutes = 0;
if($interval->days >= 1) $minutes += $interval->days * 24 * 60;
if($interval->h >= 1) $minutes += $interval->h * 60;
if($interval->i >= 1) $minutes += $interval->i;
return $minutes;
}
?>
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector