1

我在获取员工的夜间差异时遇到了问题。夜差从晚上 10 点到早上 6 点开始。

如果员工从晚上 7 点到早上 5 点 30 分上班,则应有 7 小时 30 分钟的夜间差异。

如何使用 PHP 进行计算?

非常感谢你。

4

1 回答 1

1
<?php

define('START_NIGHT_HOUR','22');
define('START_NIGHT_MINUTE','00');
define('START_NIGHT_SECOND','00');
define('END_NIGHT_HOUR','06');
define('END_NIGHT_MINUTE','00');
define('END_NIGHT_SECOND','00');

function night_difference($start_work,$end_work)
{
    $start_night = mktime(START_NIGHT_HOUR,START_NIGHT_MINUTE,START_NIGHT_SECOND,date('m',$start_work),date('d',$start_work),date('Y',$start_work));
    $end_night   = mktime(END_NIGHT_HOUR,END_NIGHT_MINUTE,END_NIGHT_SECOND,date('m',$start_work),date('d',$start_work) + 1,date('Y',$start_work));

    if($start_work >= $start_night && $start_work <= $end_night)
    {
        if($end_work >= $end_night)
        {
            return ($end_night - $start_work) / 3600;
        }
        else
        {
            return ($end_work - $start_work) / 3600;
        }
    }
    elseif($end_work >= $start_night && $end_work <= $end_night)
    {
        if($start_work <= $start_night)
        {
            return ($end_work - $start_night) / 3600;
        }
        else
        {
            return ($end_work - $start_work) / 3600;
        }
    }
    else
    {
        if($start_work < $start_night && $end_work > $end_night)
        {
            return ($end_night - $start_night) / 3600;
        }
        return 0;
    }
}

var_dump(night_difference(strtotime('today 19:00'),strtotime('tomorrow 05:30')));
var_dump(night_difference(strtotime('today 10:00'),strtotime('today 19:00')));
var_dump(night_difference(strtotime('yesterday 10:00'),strtotime('today 08:00')));
var_dump(night_difference(strtotime('yesterday 23:00'),strtotime('today 04:00')));

输出:

float(7.5)
int(0)
int(8)
int(5)
于 2012-05-10T12:34:15.623 回答