如何找到两个日期之间的星期一或星期二的数量?

时间:2009-10-31 09:33:32

标签: php date

我有开始日期和结束日期。

我需要找出星期日或星期一等的日子,具体取决于用户点击复选框。

如何在PHP中查找/计算?

10 个答案:

答案 0 :(得分:9)

w35I3y的答案几乎是正确的,但我使用该功能时遇到错误。此函数可以正确计算星期一的数量或两个给定日期之间的任何特定日期:

/** 
* Counts the number occurrences of a certain day of the week between a start and end date
* The $start and $end variables must be in UTC format or you will get the wrong number 
* of days  when crossing daylight savings time
* @param - $day - the day of the week such as "Monday", "Tuesday"...
* @param - $start - a UTC timestamp representing the start date
* @param - $end - a UTC timestamp representing the end date
* @return Number of occurences of $day between $start and $end
*/
function countDays($day, $start, $end)
{        
    //get the day of the week for start and end dates (0-6)
    $w = array(date('w', $start), date('w', $end));

    //get partial week day count
    if ($w[0] < $w[1])
    {            
        $partialWeekCount = ($day >= $w[0] && $day <= $w[1]);
    }else if ($w[0] == $w[1])
    {
        $partialWeekCount = $w[0] == $day;
    }else
    {
        $partialWeekCount = ($day >= $w[0] || $day <= $w[1]);
    }

    //first count the number of complete weeks, then add 1 if $day falls in a partial week.
    return floor( ( $end-$start )/60/60/24/7) + $partialWeekCount;
}

示例用法:

$start = strtotime("tuesday UTC");    
$end = strtotime("3 tuesday UTC");       
echo date("m/d/Y", $start). " - ".date("m/d/Y", $end). " has ". countDays(0, $start, $end). " Sundays";

输出类似于: 09/28/2010 - 2010年10月19日有3个星期日。

答案 1 :(得分:8)

没有循环,没有递归

<?php
define('ONE_WEEK', 604800); // 7 * 24 * 60 * 60

function number_of_days($days, $start, $end) {
    $w = array(date('w', $start), date('w', $end));
    $x = floor(($end-$start)/ONE_WEEK);
    $sum = 0;

    for ($day = 0;$day < 7;++$day) {
        if ($days & pow(2, $day)) {
            $sum += $x + ($w[0] > $w[1]?$w[0] <= $day || $day <= $w[1] : $w[0] <= $day && $day <= $w[1]);
        }
    }

    return $sum;
}

//$start = $end = time();

// 0x10 == pow(2, 4) == 1 << 4 // THURSDAY
// 0x20 == pow(2, 5) == 1 << 5 // FRIDAY
echo number_of_days(0x01, $start, $end); // SUNDAY
echo number_of_days(pow(2, 0), $start, $end); // SUNDAY
echo number_of_days(0x02, $start, $end); // MONDAY
echo number_of_days(pow(2, 1), $start, $end); // MONDAY
echo number_of_days(0x04, $start, $end); // TUESDAY
echo number_of_days(1 << 2, $start, $end); // TUESDAY
echo number_of_days(0x08, $start, $end); // WEDNESDAY
echo number_of_days(1 << 3, $start, $end); // WEDNESDAY
echo number_of_days(0x10, $start, $end); // THURSDAY
echo number_of_days(0x20, $start, $end); // FRIDAY
echo number_of_days(0x40, $start, $end); // SATURDAY
echo number_of_days(0x01 | 0x40, $start, $end); // WEEKENDS : SUNDAY | SATURDAY
echo number_of_days(0x3E, $start, $end); // WORKDAYS : MONDAY | TUESDAY | WEDNESDAY | THURSDAY | FRIDAY
?>

答案 2 :(得分:7)

这个问题只是迫切需要使用PHP的DateTime类的更新答案,所以这里是: -

/**
 * @param String $dayName eg 'Mon', 'Tue' etc
 * @param DateTimeInterface $start
 * @param DateTimeInterface $end
 * @return int
 */
function countDaysByName($dayName, \DateTimeInterface $start, \DateTimeInterface $end)
{
    $count = 0;
    $interval = new \DateInterval('P1D');
    $period = new \DatePeriod($start, $interval, $end);

    foreach($period as $day){
        if($day->format('D') === ucfirst(substr($dayName, 0, 3))){
            $count ++;
        }
    }
    return $count;
}

答案 3 :(得分:6)

您可以创建一个递归使用strtotime()来计算天数的函数。由于strtotime("next monday");工作得很好。

function daycount($day, $startdate, $counter)
{
    if($startdate >= time())
    {
        return $counter;
    }
    else
    {
        return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
    }
}

echo daycount("monday", strtotime("01.01.2009"), 0);

希望这是你正在寻找的东西:)

答案 4 :(得分:2)

<?php
$date = strtotime('2009-01-01');
$dateMax = strtotime('2009-02-23');

$nbr = 0;
while ($date < $dateMax) {
  var_dump(date('Y-m-d', $date));
  $nbr++;
  $date += 7 * 24 * 3600;
}
echo "<pre>";
 var_dump($nbr);
?>

答案 5 :(得分:2)

计算两个日期之间的星期五##

$from_date=(2015-01-01);

$to_date=(2015-01-20);

while(strtotime($from_date) <= strtotime($to_date)){

    //5 for count Friday, 6 for Saturday , 7 for Sunday

    if(date("N",strtotime($from_date))==5){
        $counter++;
    }
    $from_date = date ("Y-m-d", strtotime("+1 day", strtotime($from_date)));

}

echo $counter;

答案 6 :(得分:0)

function daycount($day, $startdate, $enddate, $counter) {
    if($startdate >= $enddate) {
        return $counter-1;  // A hack to make this function return the correct number of days.
    } else {
        return $this->daycount($day, strtotime("next ".$day, $startdate), $enddate, ++$counter);
    }
}

这是第一个答案的不同版本,它起点和终点,对我有用。由于某种原因,本页面上给出的所有示例似乎都会返回答案加上额外的一天。

答案 7 :(得分:0)

w35l3y的回答似乎运作良好,所以我对它进行了投票。尽管如此,我更喜欢更容易理解的东西,并且减少数学和循环(不确定从性能角度来看是否重要)。我想我已经涵盖了所有可能的场景......这就是我想出的:

function numDays($sday, $eday, $i, $cnt) {
    if (($sday < $eday && $i >= $sday && $i <= $eday) || ($sday > $eday && ($i >= $sday || $i <= $eday))) {
        // partial week (implied by $sday != $eday), so $i (day iteration) may have occurred one more time
        // a) end day is ahead of start day; $i is within start/end of week range
        // b) start day is ahead of end day (i.e., Tue start, Sun end); $i is either in back half of first week or front half of second week
        $cnt++;
    } elseif ($sday == $eday && $i == $sday) {
        // start day and end day are the same, and $i is that day, i.e., Tue occurs twice from Tue-Tue (1 wk, so $wks = $cnt)
        $cnt++;
    }

    return $cnt;    // # of complete weeks + partial week, if applicable
}

注意:$ sday和$ eday是对应于要检查的范围的开始和结束的日期数字,$ i是要计算的日期数字(我在0-6循环中有它)。我把$ wks移到了函数之外,因为每次都没有重新计算它。

$wks = floor(($endstamp - $startstamp)/7*24*60*60);
$numDays = numDays($sday, $eday, $i, $wks);

确保您比较的开始/结束时间戳具有相同的时区调整(如果有的话),否则您将总是与$ cnt和$ wks略微偏离。 (从未经调整的第一年到调整后的日期/时间X计算时,我遇到了这种情况。)

答案 8 :(得分:0)

正确的日数。这将计算在给定日期之间的周一至周日的所有天数

 <?php

    $startdate='2018-04-01';
    $enddate='2018-04-20';

    $mondayCount = 0;
    $tuesday = 0;
    $wednesday = 0;
    $thursday = 0;

    $friday = 0;
    $saturday = 0;
    $sunday = 0;

    $begin = new DateTime($startdate );
    $end = new DateTime( $enddate );
    $end = $end->modify( '+1 day' );

    $interval = new DateInterval('P1D');
    $daterange = new DatePeriod($begin, $interval ,$end);
    // looping each days from FROM and TO dates

    foreach($daterange as $date) {
        //$eachDate = $date->format("d-m-Y");
        echo $eachDateName = $date->format("l");
        switch ($eachDateName)
        {
            case 'Monday' :
                $mondayCount++;break;
            case 'Tuesday' :
                $tuesday++;break;
            case 'Wednesday' :
                $wednesday++;break;
            case 'Thursday' :
                $thursday++;break;
            case 'Friday' :
                $friday++;break;
            case 'Saturday' :
                $saturday++;break;
            case 'Sunday' :
                $sunday++;break;
        }

    }
    echo $mondayCount;echo "---";
    echo $tuesday;echo "---";
    echo $wednesday;echo "---";
    echo $thursday;echo "---";
    echo $friday;echo "----";
    echo $saturday;echo "---";
    echo $sunday;
?>

希望这会有所帮助

答案 9 :(得分:-1)

我得到了答案。它只在周日工作。但我不知道如何再做一天

<?php

// Define a constant of 1 day in seconds
define(ONE_DAY, 86400); 
date_default_timezone_set('America/New_York'); 

// Accepts two timestamps, start and end 
// Returns an array of timestamps that fall on a sunday 
function sundays_in_range($start, $end) {    
    echo date('N', $start);
    echo "<br/>";                     
    $days_until_sunday = date('w', $start) > 0 ? 7 - date('w', $start) : 0; 

    $date = $start + (ONE_DAY * $days_until_sunday); 
    $sundays = array(); 
    while ($date <= $end) { 
        array_push($sundays, $date); 
        $date += (7 * ONE_DAY); 
    } 
    return $sundays; 
} 

// Calculate some example dates. Today, and 30 days from now 
$start = time($start); 
$end = time($end) + (30 * ONE_DAY); 
echo ONE_DAY;
echo "<br/>";
 $count=0;
// Loop and output Y-m-d 
foreach (sundays_in_range($start, $end) as $sunday)
{
print "<option>".date("Y-m-d", $sunday)."</option><br/>";
 $count++;
 }

echo  $count;
?>