0

如何在 PHP 的日期范围内获取所有星期的开始日期和结束日期?

周开始 = 周日,周末 = 周六

输入

$start_date='2013-02-01'
$end_date = '2013-02-28'

输出

开始日期='2013-02-01' 结束日期='2013-02-02'
开始日期='2013-02-03' 结束日期='2013-02-09'
开始日期='2013-02-10'结束日期 ='2013-02-16'
开始日期 ='2013-02-17' 结束日期 ='2013-02-23'
开始日期 ='2013-02-24' 结束日期 ='2013-02-28'

下面的代码返回给定日期的星期开始和结束

 function getWeekDates($date)
{
    $week =  date('W', strtotime($date));
    $year =  date('Y', strtotime($date));
    $from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
    $to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));   //Returns the date of sunday in week
    echo "Start Date-->".$from."End Date -->".$to;//Output : Start Date-->2012-09-03 End Date-->2012-09-09
}

我怎样才能得到上面的结果?

4

3 回答 3

3

试试这个...

$start_date = date('Y-m-d', strtotime('2013-02-01'));
$end_date = date('Y-m-d', strtotime('2013-02-28'));
$end_date1 = date('Y-m-d', strtotime('2013-02-28 + 6 days'));

for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
    echo getWeekDates($date, $start_date, $end_date);
    echo "\n";
}

function getWeekDates($date, $start_date, $end_date)
{
    $week =  date('W', strtotime($date));
    $year =  date('Y', strtotime($date));
    $from = date("Y-m-d", strtotime("{$year}-W{$week}+1")); //Returns the date of monday in week
    if($from < $start_date) $from = $start_date;
    $to = date("Y-m-d", strtotime("{$year}-W{$week}-6"));   //Returns the date of sunday in week
    if($to > $end_date) $to = $end_date;
    echo "Start Date-->".$from."End Date -->".$to;//Output : Start Date-->2012-09-03 End Date-->2012-09-09
}  

请参阅键盘

于 2013-02-04T12:28:58.417 回答
2

我的答案。

$start_date = '2013-02-01';
$end_date = '2013-02-28';

getWeekDates($start_date, $end_date);

function getWeekDates($date, $enddate) {
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}-1")); //Returns the date of monday in week
$to = date("Y-m-d", strtotime("{$year}-W{$week}-7"));   //Returns the date of sunday in week
$Edate = strtotime($enddate);
$Sdate = strtotime($to);
if ($Edate <= $Sdate) {
    echo "<br>Start Date-->" . $from . "End Date -->" . $enddate; //Output : Start Date-->2012-09-03 End Date-->2012-09-09

} else {
    echo "<br>Start Date-->" . $from . "End Date -->" . $to; //Output : Start Date-->2012-09-03 End Date-->2012-09-09
    $to = date("Y-m-d", strtotime("$to +1days")); //Returns the date of monday in week
    getWeekDates($to, $enddate);
}
}
于 2013-02-04T11:08:20.767 回答
0

我希望我能正确回答你的问题。

你需要做的是用开始日期调用你的函数,然后在开始日期加上 7 天,然后再次调用你的函数......你必须这样做,直到你到达结束日期。

这是一些未经测试的代码:

$current_date = strtotime($start_date);
$end_date_as_date = strtotime($end_date);

while($current_date < $end_date_as_date){
getWeekDates($current_date);
$current_date= strtotime("+7 day", $current_date);
}

希望这可以帮助。如果您需要任何进一步的信息,请发表评论。

于 2013-02-04T10:32:06.527 回答