查找两个日期之间的每个周日

时间:2009-07-02 12:32:03

标签: php

我有$fromdate$todate个变量。我想要一个函数,可以在PHP中计算$fromdate$todate之间存在的每个星期日的日期。

4 个答案:

答案 0 :(得分:11)

假设这些是日期对象,从$ fromdate开始,向它添加一天,直到该日期为星期日,并且只要日期在$ todate之前。在您找到的每个星期日添加7天,添加该日期并继续,只要新日期在$ todate之前。跟踪以这种方式找到的每个日期。

答案 1 :(得分:8)

使用此功能:

function getDateForSpecificDayBetweenDates($startDate, $endDate, $weekdayNumber)
{
    $startDate = strtotime($startDate);
    $endDate = strtotime($endDate);

    $dateArr = array();

    do
    {
        if(date("w", $startDate) != $weekdayNumber)
        {
            $startDate += (24 * 3600); // add 1 day
        }
    } while(date("w", $startDate) != $weekdayNumber);


    while($startDate <= $endDate)
    {
        $dateArr[] = date('Y-m-d', $startDate);
        $startDate += (7 * 24 * 3600); // add 7 days
    }

    return($dateArr);
}

函数调用获取2010年所有星期日的日期:

$dateArr = getDateForSpecificDayBetweenDates('2010-01-01', '2010-12-31', 0);

print "<pre>";
print_r($dateArr);

重新:

Array
(
    [0] => 2010-01-03
    [1] => 2010-01-10
    [2] => 2010-01-17
    [3] => 2010-01-24
    [4] => 2010-01-31
    [5] => 2010-02-07

     ................
     ................
     ................

    [47] => 2010-11-28
    [48] => 2010-12-05
    [49] => 2010-12-12
    [50] => 2010-12-19
    [51] => 2010-12-26
)

答案 2 :(得分:3)

试试这个

function getDateForSpecificDayBetweenDates($start, $end, $weekday = 0){

$weekdays="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday";

$arr_weekdays=split(",", $weekdays);
$weekday = $arr_weekdays[$weekday];
if(!$weekday)
    die("Invalid Weekday!");

$start= strtotime("+0 day", strtotime($start) );
$end= strtotime($end);

$dateArr = array();
$friday = strtotime($weekday, $start);
while($friday <= $end)
{
    $dateArr[] = date("Y-m-d", $friday);
    $friday = strtotime("+1 weeks", $friday);
}
$dateArr[] = date("Y-m-d", $friday);

return $dateArr;
}

以下是如何调用此函数...

$dateArr = getDateForSpecificDayBetweenDates("Today", "+1 year", 0); // 0 Sun, 1 Mon, etc.

$start$end日期将采用strtotime()支持的任何内容。

答案 3 :(得分:0)

PHP date()mktime()函数可以帮助您实现目标!