2013-02-05 88 views
1

我想在PHP的日期範圍內獲取兩週的開始日期和結束日期。在PHP日期範圍內開始日期和結束日期在PHP

周開始=週日和週末=週六

IE),例如,如果日期範圍是

$開始= '2013-01-01' 和
$結束='2013- 02-28'

所需的結果

開始日期 - > 2013-01-01結束日期 - > 2013-01-12
開始日期 - > 2013-01-13結束日期 - > 2013-01-26
開始日期 - > 2013-01-27結束日期 - > 2013-02-09
開始日期 - > 2013-02-10結束日期 - > 2013-02-23
開始日期 - > 2013-02-24結束日期 - > 2013年2月28日

代碼

<?php 
$st = '2013-01-01'; 
$et ='2013-02-28'; 
$start_date = date('Y-m-d', strtotime($st)); 
$end_date = date('Y-m-d', strtotime($et)); 
$end_date1 = date('Y-m-d', strtotime($et. '+ 6 days')); 

$weekfrom = array(); 
$weekto = array(); 

for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 14 days'))) 
{ 

    $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;  

    } 
    if($from < $to) 
    { 
    array_push($weekfrom,$from); 
    array_push($weekto,$to); 
    } 

} 
$n = count($weekfrom); 

for($i = 0;$i<$n;$i++) 
{ 
    echo "Start Date-->".$weekfrom[$i]; 
    echo " End Date -->".$weekto[$i]."\n"; 
} 


?> 

當前結果

開始日期 - > 2013-01-01結束日期 - > 2013年1月5日
開始日期 - > 2013年1月13日結束日期 - > 2013-01 -19
開始日期 - > 2013-01-27結束日期 - > 2013-02-02
開始日期 - > 2013-02-10結束日期 - > 2013-02-16
開始日期 - > 2013年2月24日結束日期 - > 2013年2月28日

DEMO

在當前結果中,開始日期是正確的。但問題在結束日期之內。幫我找到問題

+0

基於開始日期和結束日期之間的區別的模式是什麼? – Develoger

回答

2

只要改變這一個...

$to = date("Y-m-d", strtotime("{$year}-W{$week}-6 + 1 week")); 

Codepad

+0

你太棒了。非常感謝你 – Nandu

+0

再次抓住你.. !! :) –

0

第一天:

if is Sunday == true 
today 
else 
strtotime('last sunday'); 

最後一天:

if is Saturday == true 
today 
else 
strtotime('next saturday'); 
相關問題