gpt4 book ai didi

php - 两个日期之间的差异(以分钟为单位,不包括周末和节假日)

转载 作者:可可西里 更新时间:2023-11-01 01:01:46 27 4
gpt4 key购买 nike

我是 PHP 编程的新手,遇到了一个有趣的问题。我尝试了多次搜索并找到了不同的解决方案,但没有一个适合我的确切问题。

我有 2 个 mysql 格式的日期戳(例如 2014-04-10 09:00:00)。我需要知道这 2 个时间戳之间的分钟差,但必须排除下类时间、周末和节假日。

例如,今天的时间戳 (2014-04-11 14:00:00) 和星期一的时间戳 (2014-04-14 11:00:00) 必须显示为 390 分钟的结果(工作日是08.30 至 18.00)。

stackexchange 上的所有解决方案都以小时或天的形式显示结果,但我需要更高的准确性。

提前致谢,如有不明之处,我们深表歉意。

最佳答案

使用示例:

$from = '2013-09-06 15:45:32';
$to = '2013-09-14 21:00:00';
echo some_func_name($from, $to);

输出:

1 day, 22 hours, 14 minutes, 28 seconds

功能:

function some_func_name($from, $to) {
$workingDays = [1, 2, 3, 4, 5]; # date format = N
$workingHours = ['from' => ['08', '00'], 'to' => ['17', '00']];

$start = new DateTime($from);
$end = new DateTime($to);

$startP = clone $start;
$startP->setTime(0, 0, 0);
$endP = clone $end;
$endP->setTime(23, 59, 59);
$interval = new DateInterval('P1D');
$periods = new DatePeriod($startP, $interval, $endP);

$sum = [];
foreach ($periods as $i => $period) {
if (!in_array($period->format('N'), $workingDays)) continue;

$startT = clone $period;
$startT->setTime($workingHours['from'][0], $workingHours['from'][1]);
if (!$i && $start->diff($startT)->invert) $startT = $start;

$endT = clone $period;
$endT->setTime($workingHours['to'][0], $workingHours['to'][1]);
if (!$end->diff($endT)->invert) $endT = $end;

#echo $startT->format('Y-m-d H:i') . ' - ' . $endT->format('Y-m-d H:i') . "\n"; # debug

$diff = $startT->diff($endT);
if ($diff->invert) continue;
foreach ($diff as $k => $v) {
if (!isset($sum[$k])) $sum[$k] = 0;
$sum[$k] += $v;
}
}

if (!$sum) return 'ccc, no time on job?';

$spec = "P{$sum['y']}Y{$sum['m']}M{$sum['d']}DT{$sum['h']}H{$sum['i']}M{$sum['s']}S";
$interval = new DateInterval($spec);
$startS = new DateTime;
$endS = clone $startS;
$endS->sub($interval);
$diff = $endS->diff($startS);

$labels = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$return = [];
foreach ($labels as $k => $v) {
if ($diff->$k) {
$return[] = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
}
}

return implode(', ', $return);
}

这个函数可以更短/更好;但那是你现在的工作 ;)

如果您希望排除节假日,请参见以下示例:https://stackoverflow.com/a/19221403/67332

关于php - 两个日期之间的差异(以分钟为单位,不包括周末和节假日),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23011869/

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