【发布时间】:2010-06-02 14:34:01
【问题描述】:
如何在php中计算两个日期之间的星期六和星期日的数量?
有没有为此目的的内置函数?
【问题讨论】:
如何在php中计算两个日期之间的星期六和星期日的数量?
有没有为此目的的内置函数?
【问题讨论】:
这里已经有一个相关的问题,Calculate business days
您可以使用它从 7 中减去以获得周末天数或类似天数。
【讨论】:
我认为没有内置的,但这应该可以完成工作:
$startTime = START_TIMESTAMP;
$endTime = END_TIMESTAMP;
$time = $startTime;
$count = 0;
while(date('w', $time) != 0) { // 0 (for Sunday) through 6 (for Saturday)
$time += 86400;
}
while($time < $endTime) {
$count++;
$time += 7 * 86400;
}
【讨论】:
date('w', $time) == 0 所以你去第二个,而$count++,你至少有一个星期六。
$time = strtotime("Saturday") 或$time = strtotime("Sunday") 而不是while(date('w', $time) != 0)。
让我们都亲吻(保持简单愚蠢)。为什么搞得这么复杂?
function countWeekendDays($start, $end)
{
// $start in timestamp
// $end in timestamp
$iter = 24*60*60; // whole day in seconds
$count = 0; // keep a count of Sats & Suns
for($i = $start; $i <= $end; $i=$i+$iter)
{
if(Date('D',$i) == 'Sat' || Date('D',$i) == 'Sun')
{
$count++;
}
}
return $count;
}
【讨论】:
你可以像这样在数学上计算它 - Based on Roland's Answer
private function getNumberOfWeekendDays(\DateTimeInterface $startDate, \DateTimeInterface $endDate): int
{
$startNumber = (int) $startDate->format('N');
$endNumber = (int) $endDate->format('N');
$daysBetweenStartAndEnd = $endDate->diff($startDate)->d;
$weekendDays = (int) (2 * ($daysBetweenStartAndEnd + $startNumber) / 7);
$weekendDays = $weekendDays - ($startNumber == 7 ? 1 : 0) - ($endNumber == 7 ? 1 : 0);
return $weekendDays;
}
【讨论】:
<?php
date_default_timezone_set("Europe/Lisbon");
$d1 = new DateTime("2009-06-01"); /* inclusive */
$d2 = new DateTime("2009-07-01"); /* exclusive */
$interval = $d2->diff($d1);
$number_of_days = $interval->format("%d");
$number_of_weekends = $number_of_days / 7;
$remainder = $number_of_days % 7;
if ($remainder >=2 && $d1->format("D") == "Sat")
$number_of_weekends++;
elseif ($d1->format("w") + $remainder >= 8)
$number_of_weekends++;
我可能在最后一个条件中错过了一个,请务必使用不同的开始日期进行检查。 (如果您发现错误,请随时编辑此答案)。
【讨论】:
绝对没有内置函数,但您可以使用 strtotime 循环天数
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-09');
function numWeekdays( $start_ts, $end_ts, $day, $include_start_end = false ) {
$day = strtolower( $day );
$current_ts = $start_ts;
// loop next $day until timestamp past $end_ts
while( $current_ts < $end_ts ) {
if( ( $current_ts = strtotime( 'next '.$day, $current_ts ) ) < $end_ts) {
$days++;
}
}
// include start/end days
if ( $include_start_end ) {
if ( strtolower( date( 'l', $start_ts ) ) == $day ) {
$days++;
}
if ( strtolower( date( 'l', $end_ts ) ) == $day ) {
$days++;
}
}
return (int)$days;
}
echo numWeekDays( $start, $end, 'saturday', false );
【讨论】:
我搜索了一段时间,寻找一个可行的简单解决方案,并决定自己编写并想出了这个
$start = date('Y-m-d');
$end = date('Y-m-d', strtotime($start.' +1 year'));
$current = $start;
$count = 0;
while($current != $end){
if(date('l', strtotime($current)) == 'Saturday'){
$count++;
}
$current = date('Y-m-d', strtotime($current.' +1 day'));
};
echo $count;
【讨论】: