2016-12-27 65 views
0

我需要創建一個日期時間與特定的一天每個月之間的開始日期和結束日期。 實施例:PHP創建日期時間與特定的一天,每兩個日期之間mounth

  • 具體天:04
  • 開始:2016年12月22日
  • 結束:2017年3月6日
  • 需要輸出:2016年1月4日; 2016-02-04; 2016-03-04

我該怎麼做?

+1

如果你已經找到了答案,那你爲什麼已經在這裏發佈了問題.. !!! –

+0

@SaumyaRastogi總的來說,發表問題的唯一目的是回答問題沒有任何錯誤。 –

+0

@SaumyaRastogi我發佈了這個問題,因爲我很長時間沒有找到它的答案。通過努力,我自己就到了那裏。我認爲,因爲我沒有在網絡上找到解決方案,我打算將它發佈給未來的開發人員誰會尋找解決方案 –

回答

-1

我找到了!這下面的代碼爲我工作:

$d1 = new DateTime("2016-12-22"); 
$d2 = new DateTime("2017-03-06"); 
$dd = '04'; 

if ($dd < $d1->format('d')) { 
    $d1->add(new \DateInterval('P1M')); 
    $date = $dd.'-'.$d1->format('m').'-'.$d1->format('Y'); 

} else { 
    $date = $d1->format('Y').'-'.$d1->format('m').'-'.$dd; 
} 

$date = new DateTime($date); 
print_r($date);echo('<br />'); 

while ($date->add(new \DateInterval('P1M')) <= $d2){ 
    $d1->add(new \DateInterval('P1M')); 
    $date = $dd.'-'.$d1->format('m').'-'.$d1->format('Y'); 
    $date = new DateTime($date); 
    print_r($date);echo('<br />'); 
} 
0

您可以創建一個DatePeriod對象,並遍歷它來得到你需要的所有日期:

$start = new DateTime('2016-12-22'); 
$end = new DateTime('2017-03-06'); 

// Compute the occurrence on the same month as $start 
$first = new DateTime(); 
$first->setDate($start->format('Y'), $start->format('m'), 4); 

// If it is in the past of $start then the first occurrence is on the next month 
if ($first < $start) { 
    $first->add(new DateInterval('P1M')); 
} 

// Create a DatePeriod object that iterates between $first and $end 
// in increments of 1 month 
$period = new DatePeriod($first, new DateInterval('P1M'), $end); 

// Run through the list, process each item 
foreach ($period as $day) { 
    echo($day->format('Y-m-d')."\n"); 
} 
相關問題