-->

Calculate time length based on two given times

2019-08-27 22:25发布

问题:

Need help to calculate $work_in_daytime and $work_in_nighttime.

$nightStart = '22:00';
$nightEnd = '07:00';

$workers = array(
    '0' => array(
        'name'  => 'Lyons',
        'start' => '15:15',
        'end'   => '23:45'
    ),

    '1' => array(
        'name'  => 'Santos',
        'start' => '10:00',
        'end'   => '22:00'
    ),

    '2' => array(
        'name'  => 'Montgomery',
        'start' => '22:30',
        'end'   => '08:00'
    )
); 


foreach ($workers as $worker) {
    $length_of_work = abs(strtotime($worker['start']) - strtotime($worker['end'])) / 3600;
    $work_in_daytime = '';
    $work_in_nighttime = '';
}

Thanks for your help.

回答1:

If the start to end spans the night-start or night-end, you need to split the work time into separate items. I would suggest converting to datetime objects and using dateinterval to make it easy to get duration.



回答2:

  <?php
    $start_time = strtotime("2017-09-01 10:42:00");
    $end_time = strtotime("2017-09-02 10:21:00");
    //Divide seconds by 60 to get minutes or whatever is appropriate and round off
    echo $difference = round(abs($to_time - $from_time) / 60,2). " minutes";
?>