2个日期之间的时差,忽略周末时间 [英] Time difference between 2 dates ignoring weekend time
问题描述
给出2个日期,我如何计算它们之间的小时/分钟数,不包括周末时间(自星期五17:30到星期一09:00)
Given 2 dates, how can i calculate the number of hours/minutes between them, excluding weekend time (since Friday 17:30 till Monday 09:00)
该脚本查询MySql数据库,但是我认为这种计算在php中会更容易.我正在考虑一个迭代函数来确定工作日,并一直循环直到最后一个日期小于当前日期指示器?
The script queries a MySql database but i assume this sort of calculations would be easier in php. I'm thinking of a iterative function to determine the weekday and keep looping until last date would be smaller than current day indicator?
有什么建议吗?
推荐答案
假设您有两个时间戳: $ timestamp1
和 $ timestamp2
,则可以减去它们并减去周末数: $ difference-($ weekends * 2 * 24 * 3600)
.
Assuming that you have two timestamps: $timestamp1
and $timestamp2
, you could just subtract them and subtract the number of weekends: $difference - ($weekends*2*24*3600)
.
function difWeekends($timestamp1, $timestamp2){
$difference = $timestamp2 - $timestamp1;
$nextWeekend = strtotime('next Saturday', $timestamp1);
$weekends = 0;
$weekendFound = true;
while($weekendFound){
if($nextWeekend < $timestamp2){
$weekendFound = false;
} else {
$nextWeekend = strtotime('+7 days', $nextWeekend);
$weekends++;
}
}
$difference -= $weekends*48*60*60;
$hours = $difference % 3600; // Not sure about this, I assume you already got this...
$difference -= $hours*3600;
$minutes = $difference % 60;
return array('hours'=>$hours, 'minutes'=>$minutes);
}
需要
function difWeekends($timestamp1, $timestamp2){
$difference = $timestamp2 - $timestamp1;
// Calculate the start of the first next weekend
$nextWeekendStart = strtotime('next Friday 17:30', $timestamp1);
// Calculate the end of the first next weekend
$nextWeekendEnd = strtotime('next Monday 9:00', $nextWeekendStart);
// This wil hold the number of weekend-seconds that needs to be subtracted
$weekendSubtract = 0;
$weekendFound = true;
while($weekendFound){
// If $timestamp2 ends before the next weekend, no weekend is found. [] = weekends, --- is time range
// --- [ ]
if($timestamp2 < $nextWeekendStart){
$weekendFound = false;
} else {
// ----[-- ]
if($timestamp2 < $nextWeekendEnd){
$weekendSubtract += $timestamp2-$nextWeekendStart;
$weekendFound = false; // Last weekend was found
} else {
// ---[----]---
$weekendSubtract += $nextWeekendEnd - $nextWeekendStart;
$nextWeekendStart += 7*24*60*60;
$nextWeekendEnd += 7*24*60*60;
}
}
}
$difference -= $weekendSubtract;
$hours = $difference % 3600; // Not sure about this, I assume you already got this...
$difference -= $hours*3600;
$minutes = $difference % 60;
return array('hours'=>$hours, 'minutes'=>$minutes);
}
这篇关于2个日期之间的时差,忽略周末时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!