gpt4 book ai didi

php - 计算两个日期之间的工作时间

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:53:29 30 4
gpt4 key购买 nike

我需要一个 PHP 方法来根据 8 小时工作日计算两个日期之间的工作时间,不包括周末和银行假日。

例如 2012-01-01T08:30:002012-01-05T10:30:00 之间的工作时间差实际上是 26 个工作小时,因为前两天是周末/银行假期,只剩下 3 个工作日和 2 小时的时差,即 3*8+2=26

我用过@flamingLogos excellent answer to a previous question但无法将时间和日期考虑在内。

最佳答案

下面的函数计算两个日期之间的工作时间,以文本格式提供,例如“2013-11-27 13:40”,工作时间从 9 点到 17 点(可以更改)。

function get_working_hours($from,$to)
{
// timestamps
$from_timestamp = strtotime($from);
$to_timestamp = strtotime($to);

// work day seconds
$workday_start_hour = 9;
$workday_end_hour = 17;
$workday_seconds = ($workday_end_hour - $workday_start_hour)*3600;

// work days beetwen dates, minus 1 day
$from_date = date('Y-m-d',$from_timestamp);
$to_date = date('Y-m-d',$to_timestamp);
$workdays_number = count(get_workdays($from_date,$to_date))-1;
$workdays_number = $workdays_number<0 ? 0 : $workdays_number;

// start and end time
$start_time_in_seconds = date("H",$from_timestamp)*3600+date("i",$from_timestamp)*60;
$end_time_in_seconds = date("H",$to_timestamp)*3600+date("i",$to_timestamp)*60;

// final calculations
$working_hours = ($workdays_number * $workday_seconds + $end_time_in_seconds - $start_time_in_seconds) / 86400 * 24;

return $working_hours;
}

还有两个附加功能。一个返回工作日数组...

function get_workdays($from,$to) 
{
// arrays
$days_array = array();
$skipdays = array("Saturday", "Sunday");
$skipdates = get_holidays();

// other variables
$i = 0;
$current = $from;

if($current == $to) // same dates
{
$timestamp = strtotime($from);
if (!in_array(date("l", $timestamp), $skipdays)&&!in_array(date("Y-m-d", $timestamp), $skipdates)) {
$days_array[] = date("Y-m-d",$timestamp);
}
}
elseif($current < $to) // different dates
{
while ($current < $to) {
$timestamp = strtotime($from." +".$i." day");
if (!in_array(date("l", $timestamp), $skipdays)&&!in_array(date("Y-m-d", $timestamp), $skipdates)) {
$days_array[] = date("Y-m-d",$timestamp);
}
$current = date("Y-m-d",$timestamp);
$i++;
}
}

return $days_array;
}

第二个 - 返回假期数组

function get_holidays() 
{
// arrays
$days_array = array();

// You have to put there your source of holidays and make them as array...
// For example, database in Codeigniter:
// $days_array = $this->my_model->get_holidays_array();

return $days_array;
}

关于php - 计算两个日期之间的工作时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8914360/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com