如何计算2个日期之间的会话数(12 AM-AMAM)

时间:2016-08-12 15:53:36

标签: php

我需要计算2个日期之间的会话数(12 AM-AMAM)。

对于Ex

$a='12-05-2016 11:30AM'
$b='14-05-2016 9:30PM'

输出应为6

12th 11:30AM-11:59AM -->1
12TH 12:00PM-11:59PM -->2
13TH 12:00AM-11:59AM -->3
13TH 12:00PM-11:59PM -->4
14TH 12:00AM-11:59AM -->5
14TH 12:00PM-9:30PM --->6

我无法找到正确的逻辑。请帮助找到所需的解决方案

1 个答案:

答案 0 :(得分:0)

  

您可以尝试以下功能...进行测试,转到here

<?php

    $a          = '12-05-2016 11:30AM';
    $b          = '14-05-2016 9:30PM';

    function getDatesDiffInSteps($date1, $date2){
        $dateSplit1 = explode(" ", $date1); list($dA, $tA) = $dateSplit1;
        $dt1        = new DateTime($date1);
        $dt2        = new DateTime($date2);
        $baseDateA  = new DateTime($dA);
        $prDate     = new DateTime($date1);
        $i          = 1;
        $iDiff      = ($dt2->getTimestamp() - $dt1->getTimestamp());
        $diff       = $dt2->diff($dt1);
        $d           = $diff->d;
        $h          = $diff->h;
        $arr        = [];
        $prDate->setTime(0, 0, 0);

        if($iDiff > 0){
            // GET THE NEAREST 12 O'CLOCK TO THE START TIME:
            $noon       = date_create_from_format("d-m-Y H:i", "{$dA} 11:59");
            $night      = date_create_from_format("d-m-Y H:i", "{$dA} 23:59");
            if($noon>$dt1){
                $arr[]      = $dt1->format("jS h:iA") . " - " . $noon->format("H:iA") . " -->{$i}";
                $prDate->setTime(12, 0, 0);
            }else if($night>$dt1){
                $arr[]      = $dt1->format("jS h:iA") . " - " . $night->format("H:iA") . " -->{$i}";
                $prDate->setTime(24, 0, 0);
            }

            if($d){
                $h += ($d*24);
            }
            for($hr=0; $hr<=($h); $hr+=12){
                $i++;
                $lDate  = $baseDateA->add(new DateInterval("PT12H"));
                $sDate  = $prDate->add(new DateInterval("PT11H59M59S"));
                if($i < intval($h/12)+2){
                    $arr[]  = $lDate->format("jS h:iA") . " - " . $sDate->format("h:iA") . " -->{$i}";
                }else{
                    $arr[]  = $lDate->format("jS h:iA") . " - " . $dt2->format("h:iA") . " -->{$i}";
                }
            }

        }
        return $arr;
    }
    var_dump(getDatesDiffInSteps($a, $b));

    // PRODUCES:
    array (size=6)
      0 => string '12th 11:30AM - 11:59AM -->1' (length=27)
      1 => string '12th 12:00PM - 11:59PM -->2' (length=27)
      2 => string '13th 12:00AM - 11:59AM -->3' (length=27)
      3 => string '13th 12:00PM - 11:59PM -->4' (length=27)
      4 => string '14th 12:00AM - 11:59AM -->5' (length=27)
      5 => string '14th 12:00PM - 09:30PM -->6' (length=27)