2012-05-10 124 views
1

我在獲取員工的夜晚差異方面存在問題。夜晚差分從晚上10點開始到上午6點。PHP中的時間夜差計算

如果員工從晚上7點到5點半上班,應該有7小時30分鐘的夜間差別。

如何使用PHP來計算這個值?

非常感謝。

回答

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) 
+0

非常感謝你阿列克謝! :) – danzs