如何在PHP的日期范围内获取所有星期开始日期和结束日期?
周开始=周日和周末=周六
输入
$ START_DATE = '2013年2月1日'
$ 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
}
如何获得上述结果?
答案 0 :(得分: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);
}
}
答案 1 :(得分:2)
试试这个...
$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
}
请参阅 Codepad 。
答案 2 :(得分:0)
我希望我的问题正确。
您需要做的是使用开始日期调用您的函数,然后将七天添加到开始日期并再次调用您的函数...您必须这样做才能到达结束日期。
以下是一些未经测试的代码:
$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);
}
希望这会有所帮助。如果您需要任何进一步的信息,请发表评论。